I want to call a C # delegate from unmanaged C ++ code. The decimal delegate works fine, but the delegate with parameters crashed my program

Below is the function code from a non-variable dll. It takes a function pointer as an argument and simply returns the value returned by the called function.

extern __declspec(dllexport) int _stdcall callDelegate(int (*pt2Func)()); extern __declspec(dllexport) int _stdcall callDelegate(int (*pt2Func)()) { int r = pt2Func(); return r; } 

In C # managed code, I call the umanged function above with a delegate.

  unsafe public delegate int mydelegate( ); unsafe public int delFunc() { return 12; } mydelegate d = new mydelegate(delFunc); int re = callDelegate(d); [DllImport("cmxConnect.dll")] private unsafe static extern int callDelegate([MarshalAs(UnmanagedType.FunctionPtr)] mydelegate d); 

It all works great! but if I want the pointer / delegate of my function to take arguments, it crashed the program. Therefore, if I modify the code as follows, my program will work.

Modified Unmanaged C ++ -

 extern __declspec(dllexport) int _stdcall callDelegate(int (*pt2Func)(int)); extern __declspec(dllexport) int _stdcall callDelegate(int (*pt2Func)(int)) { int r = pt2Func(7); return r; } 

Modified C # Code -

 unsafe public delegate int mydelegate( int t); unsafe public int delFunc(int t) { return 12; } mydelegate d = new mydelegate(delFunc); int re = callDelegate(d); 
+4
source share
2 answers

The calling rule for the function pointer is invalid. Do it like this:

  int (__stdcall * pt2Func)(args...) 
+3
source

So this should work:

C ++ DLL:

 extern "C" __declspec(dllexport) void __stdcall doWork(int worktodo, int(__stdcall *callbackfunc)(int)); 

C # code:

 delegate int del (int work); [DllImport(@"mydll")] private static extern void doWork(int worktodo, del callback); int callbackFunc(int arg) {...} ... del d = new del(callbackFunc); doWork(1000, d); 
0
source

All Articles