Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/145.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 我想打电话给来自C++;非托管代码。无参数委托工作正常,但有参数的委托使我的程序崩溃_C#_C++_Pinvoke_Marshalling_Unmanaged - Fatal编程技术网

C# 我想打电话给来自C++;非托管代码。无参数委托工作正常,但有参数的委托使我的程序崩溃

C# 我想打电话给来自C++;非托管代码。无参数委托工作正常,但有参数的委托使我的程序崩溃,c#,c++,pinvoke,marshalling,unmanaged,C#,C++,Pinvoke,Marshalling,Unmanaged,以下是来自非托管dll的函数代码。它接受函数指针作为参数,只返回被调用函数返回的值 extern __declspec(dllexport) int _stdcall callDelegate(int (*pt2Func)()); extern __declspec(dllexport) int _stdcall callDelegate(int (*pt2Func)()) { int r = pt2Func(); return r; } 在托管C#代码中,我用一个委托调用

以下是来自非托管dll的函数代码。它接受函数指针作为参数,只返回被调用函数返回的值

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#码-


函数指针的调用约定错误。让它看起来像这样:

 int (__stdcall * pt2Func)(args...)
因此,这应该是可行的:

C++DLL:

extern "C" __declspec(dllexport) void __stdcall doWork(int worktodo, int(__stdcall *callbackfunc)(int));
C#代码:

extern "C" __declspec(dllexport) void __stdcall doWork(int worktodo, int(__stdcall *callbackfunc)(int));
delegate int del (int work);    

[DllImport(@"mydll")]
private static extern void doWork(int worktodo, del callback); 

int callbackFunc(int arg) {...} 

...

del d = new del(callbackFunc);
doWork(1000, d);