Calling managed function from unmanaged DLL

Hi there !

I need your help. I'm trying to write program, that is doing something in unmanaged part and sometimes it updates progressbar. First calls are ok, but after third i've exception:

Callback with value 1
Callback with value 2
Callback with value 3
Callback with value 1648628252

Unhandled Exception: System.AccessViolationException: Attempted to read or write
protected memory. This is often an indication that other memory is corrupt.
at DelegateForUnmanaged.MainClass.DelegateTest(IntPtr callbackFunction)
at DelegateForUnmanaged.MainClass.Main(String[] args) in g:\Eksperymenty\Dele
gateForUnmanaged\Main.cs:line 32

What is wrong

C# Code (.NET 2.0):
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;

namespace DelegateForUnmanaged
{
class MainClass
{
[DllImport("sample.dll", CallingConvention=CallingConvention.Cdecl)]
static extern unsafe void DelegateTest ( IntPtr callbackFunction );

private static void Callback ( int val )
{
Console.WriteLine("Callback with value " + val );
}

private delegate void delegateTest ( int val);
private static delegateTest dTest;

public static void Main(string[] args)
{
IntPtr d;
GCHandle gch;

dTest = new delegateTest(Callback);
gch = GCHandle.Alloc ( dTest );
d = Marshal.GetFunctionPointerForDelegate ( dTest );

GC.Collect();
GC.WaitForPendingFinalizers();

DelegateTest ( d );

gch.Free();
}
}
}

DLL Code (MinGW-5.0.3):
#include <windows.h>

#ifdef BUILD_DLL
#define DLL_EXPORT __declspec(dllexport)
#else
#define DLL_EXPORT
#endif

// a sample exported function
void DLL_EXPORT SomeFunction(const LPCSTR sometext)
{
MessageBoxA(0, sometext, "DLL Message", MB_OK | MB_ICONINFORMATION);
}

void DLL_EXPORT DelegateTest ( void (*callbackFunction)(int) )
{
int i = 0;
while ( 1 ) callbackFunction(++i);
}

BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
switch (fdwReason)
{
case DLL_PROCESS_ATTACH:
// attach to process
// return FALSE to fail DLL load
break;

case DLL_PROCESS_DETACH:
// detach from process
break;

case DLL_THREAD_ATTACH:
// attach to thread
break;

case DLL_THREAD_DETACH:
// detach from thread
break;
}
return TRUE; // succesful
}



Answer this question

Calling managed function from unmanaged DLL

  • johnny_no1_boy

    The function pointer returned by GetFunctionPointerForDelegate has __stdcall calling convention so you need to modify the C file as follows:

    void DLL_EXPORT DelegateTest ( void (__stdcall *callbackFunction)(int) )


  • Calling managed function from unmanaged DLL