以下是来自unmanged DLL功能的代码。它接受函数指针作为参数,并简单地返回被调用函数返回的值。我想从C++非托管代码调用C#委托。一个无参数的委托工作正常,但与参数的代表崩溃我的程序
extern __declspec(dllexport) int _stdcall callDelegate(int (*pt2Func)());
extern __declspec(dllexport) int _stdcall callDelegate(int (*pt2Func)())
{
int r = pt2Func();
return r;
}
在托管的C#代码中,我使用委托调用上面的umanged函数。
unsafe public delegate int mydelegate();
unsafe public int delFunc()
{
return 12;
}
mydelegate d = new mydelegate(delFunc);
int re = callDelegate(d);
[DllImport("cmxConnect.dll")]
private unsafe static extern int callDelegate([MarshalAs(UnmanagedType.FunctionPtr)] mydelegate d);
这一切都很好!但如果我想让我的函数指针/委托采取参数,它会使程序崩溃。 所以,如果我修改代码如下我的程序崩溃。
改性非托管C++ -
extern __declspec(dllexport) int _stdcall callDelegate(int (*pt2Func)(int));
extern __declspec(dllexport) int _stdcall callDelegate(int (*pt2Func)(int))
{
int r = pt2Func(7);
return r;
}
改性C#代码 -
unsafe public delegate int mydelegate(int t);
unsafe public int delFunc(int t)
{
return 12;
}
mydelegate d = new mydelegate(delFunc);
int re = callDelegate(d);