简体   繁体   中英

Calling C++ function with pointer to function 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 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.

Please check the calling convention when doing the DLLImport - this defaults to Winapi / StdCall.
Also it is important that you must keep a reference to your delegate inside the managed code during the lifetime of the application as the garbage collector will otherwise remove your delegate after a while, because the garbage collector can only count references inside the managed code. I usually keep a reference to the delegate as a static property of the class which setups the delegate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM