C ++ function call with function pointer in C # as parameter

I have the following code in Native C dll.

typedef void CallbackType( INT32 param1, INT32 param2 ); NATIVE_API void RegisterEventCallBack(CallbackType *callBackFunction); //INT32 is defined as below: typedef signed int INT32, *PINT32; 

I need to call this method from my C # code. After doing some of the solutions available on the stack, I tried this:

Delegate Declaration:

 [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void CallbackType(Int32 param1, Int32 param2); 

Method import declaration:

 [DllImport("EtIPAdapter.dll")] public static extern void RegisterEventCallBack([MarshalAs(UnmanagedType.FunctionPtr)]CallbackType callbackFunc); 

Call:

 RegisterEventCallBack(ReceivedData); private static void ReceivedData(Int32 param1, Int32 param2) { //Do something } 

But this does not work, and I get the following error:

The PInvoke function call "RegisterEventCallBack" has an unbalanced stack. This is likely due to the fact that the PInvoke managed signature does not match the unmanaged target signature. Verify that the calling agreement and PInvoke signature settings match the target unmanaged signature.

I also tried passing the function pointer that I received using GetFunctionPointerFromDelegate(ReceivedDataDelegate) . But this also leads to the same error.

The error indicates a signature mismatch, but I do not see any obvious signature mismatch. Please, help.

+4
source share
1 answer

Please check the calling convention when executing DLLImport - this is the default value for Winapi / StdCall.
It is also important that you keep the link to your delegate inside the managed code throughout the life cycle of the application, since the garbage collector would otherwise delete the delegate after a while, because the garbage collector can only count links inside the managed code. I usually keep the delegate reference as a static property of the class that the delegate sets up.

+1
source

All Articles