问题描述
以下是来自未经过编译的dll的函数的代码。它接受一个函数指针作为参数,并简单地返回被调用函数返回的值。
The Following is code of a function from a unmanged dll. It takes in a function pointer as argument and simply returns value returned by the called function.
extern __declspec(dllexport) int _stdcall callDelegate(int (*pt2Func)());
extern __declspec(dllexport) int _stdcall callDelegate(int (*pt2Func)())
{
int r = pt2Func();
return r;
}
在托管C#代码中,我使用委托调用上面的umanged函数。 p>
In managed C# code I call the umanged function above with a delegate.
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);
这一切都很好!但如果我想我的函数指针/委托接受参数,它崩溃了程序。
所以如果我修改代码如下我的程序崩溃。
This all works great !! but if I want my function pointer/delegate to take arguments it crashed the program.So if I modify the code as follows my program crashes.
修改的非托管c ++ -
Modified unmanaged 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#代码 -
Modified C# code -
unsafe public delegate int mydelegate( int t);
unsafe public int delFunc(int t)
{
return 12;
}
mydelegate d = new mydelegate(delFunc);
int re = callDelegate(d);
推荐答案
函数指针的调用约定是错误的。看起来像这样:
The calling convention for the function pointer is wrong. Make it look like this:
int (__stdcall * pt2Func)(args...)
这篇关于我想从C ++非托管代码调用一个C#委托。无参数委托工作正常,但是带参数的委托崩溃了我的程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!