c# - 使用指向 C# 中的函数的指针作为参数调用 C++ 函数

标签 c# c++ function pointers marshalling

我在 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;

我必须从我的 C# 代码中调用此方法。在遵循 stackflow 提供的一些解决方案之后,我尝试了这个:

委托(delegate)声明:

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

方法导入声明:

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

调用:

RegisterEventCallBack(ReceivedData);

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

但这不起作用,我收到以下错误:

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.

我还尝试传递使用 GetFunctionPointerFromDelegate(ReceivedDataDelegate) 获得的函数指针。但这也会导致同样的错误。

错误指出签名不匹配,但我没有看到任何明显的签名不匹配。请帮忙。

最佳答案

请在执行 DLLImport 时检查调用约定 - 默认为 Winapi/StdCall。
同样重要的是,您必须在应用程序的生命周期内在托管代码中保留对您的委托(delegate)的引用,否则垃圾收集器将在一段时间后删除您的委托(delegate),因为垃圾收集器只能对托管代码内的引用进行计数。我通常保留对委托(delegate)的引用作为设置委托(delegate)的类的静态属性。

关于c# - 使用指向 C# 中的函数的指针作为参数调用 C++ 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15899018/

相关文章:

c# - 列出超过 8 个项目的元组

c++ - Windows系统如何安装OpenDDS 3.12

C++ 类对非类型模板参数的部分特化

c++ - 与整数 vector 相乘并相加

c++ - 构造函数中的错误 : no instance of overloaded function, (C++)

c# - 如何使用IsolatedStorageFile.GetUserStoreForApplication()

c# - 使用信号量保护队列的问题

c# - 方法的参数顺序(比如命名、参数、输入、输出、可选)是什么?

c++ - 指针函数

javascript - 如何检测在javascript中单击了哪个按钮?