简体   繁体   English

调用C ++函数,指向C#中的函数作为参数

[英]Calling C++ function with pointer to function in C# as parameter

I have the following code in Native C dll. 我在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. 我必须从我的C#代码中调用此方法。 After following some solutions available at stackflow, I tried this: 在遵循stackflow提供的一些解决方案之后,我尝试了这个:

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. 对PInvoke函数'RegisterEventCallBack'的调用使堆栈失衡。 This is likely because the managed PInvoke signature does not match the unmanaged target signature. 这很可能是因为托管PInvoke签名与非托管目标签名不匹配。 Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature. 检查PInvoke签名的调用约定和参数是否与目标非托管签名匹配。

I also tried by passing the function pointer which I got using GetFunctionPointerFromDelegate(ReceivedDataDelegate) . 我也试过传递使用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. 执行DLLImport时请检查调用约定 - 默认为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. 我通常将对委托的引用保留为设置委托的类的静态属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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