【发布时间】:2015-08-26 01:31:18
【问题描述】:
我有一个 C++/Cx 库,我需要将 C# 中的回调函数作为指向它的指针传递给该库。
委托在 WinRt 层中声明如下:
public delegate void del(int, enumType, uint, string, int);
C#
void callbackFunction(
int a,
enumType b, //this is public enum class
uint c,
String d,
int e)
{
tb.Text() = d;
}
Wrc_Component.wrc w = new Wrc_Component.wrc();
del d = new d(callbackFunction);
IntPtr p = System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate(d);
w.func(p.ToInt32(), "string");
再一次在 func() 的 WinRt 层定义中:
void wrc::func(int ptrToCallback, Platform::String^ str){
void*p = (void*)ptrToCallBack;
callBackFunction cb = (callBackFunction)p;
cb(0,enumType(0),0,"aaaa",0); //here is exception thrown
}
当然代码简化了一点。 在代码中标记了引发以下异常的行:
App1.exe 中出现“System.Runtime.InteropServices.MarshalDirectiveException”类型的异常,但未在用户代码中处理
附加信息:Windows 运行时委托不能用于 PInvoke 互操作。
我还想提一下,如果我正在调用以相同方式检索的函数,但更简单,它不会引发任何异常。
是什么导致了这个异常?这是因为用户定义的枚举类型吗?
编辑
如果我需要将它进一步传递给 C++ 本地库,据我所知,我无法从 WinRt 中的委托中检索指向函数的指针。
【问题讨论】:
-
关于您的后续问题,您无法将 C# 委托传递给纯 C++ 库。必须使用 C++/CX 类型。
标签: c# windows-runtime c++-cx