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);
source share