I want to call a C# delegate from C++ unmanaged code. A parameterless delegate works fine , but a delegate with parameters crashed my program

若如初见. 提交于 2019-12-06 05:43:30

问题


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;
}

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.

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;
}

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);

回答1:


The calling convention for the function pointer is wrong. Make it look like this:

 int (__stdcall * pt2Func)(args...)



回答2:


So this should work:

C++ DLL:

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

C# Code:

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);


来源:https://stackoverflow.com/questions/3374433/i-want-to-call-a-c-sharp-delegate-from-c-unmanaged-code-a-parameterless-deleg

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!