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 have to call this method from my C# code. After following some solutions available at stackflow, I tried this:
Declaration of delegate:
[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);
Calling:
RegisterEventCallBack(ReceivedData);
private static void ReceivedData(Int32 param1, Int32 param2)
{
//Do something
}
But this doesn't work and I get the following error:
A call to PInvoke function 'RegisterEventCallBack' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.
I also tried by passing the function pointer which I got using GetFunctionPointerFromDelegate(ReceivedDataDelegate). But that also result in the same error.
Error point out to signature mismatch, but I don't see any obvious signature mismatch. Please help.
NATIVE_APImacro defined? I think the problem is with your managed declaration of theRegisterEventCallBackfunction, not the callback delegate. Are you using the right calling convention? It seems odd thatRegisterEventCallBackwould usestdcall(the default forDllImport) when its callback parameter usescdecl.