简体   繁体   English

封送C / C ++函数,在C#参数中带回调函数

[英]Marshaling C/C++ function with callback function in parameter to C#

I have the following in my native code: 我的本机代码中包含以下内容:

typedef void (__stdcall * HandlerCallBack)(float);

class ASSIMP_API NewProgressHandler : public ProgressHandler
{
    HandlerCallBack CallBack;
public:
    bool Update(float percentage = -1.f){
        if (CallBack) CallBack (percentage);
        return true;
    }

    void SetCallBack (HandlerCallBack callback) {
        CallBack = callback;
    }
};

void Importer::SetProgressHandlerCallBack (HandlerCallBack CallBack) {
   NewProgressHandler* pNewHandler = new NewProgressHandler ();
   pNewHandler->SetCallBack (CallBack);
   ProgressHandler* pHandler = pNewHandler;
   SetProgressHandler (pHandler);
}

I need to call 我需要打电话

SetProgressHandlerCallBack (HandlerCallBack CallBack)

from c# code, so I do the following: 从c#代码,所以我做了以下:

[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate void HandlerCallBack([MarshalAs(UnmanagedType.R4)]float percent);

[DllImport("my.dll")]
public static extern void SetProgressHandlerCallBack ([MarshalAs(UnmanagedType.FunctionPtr)] 
                                                      HandlerCallBack callBack);

public void AssimpCallBack ([MarshalAs(UnmanagedType.R4)]float percent) {
    Debug.Log (percent);
}



void SomeFunction () {
   HandlerCallBack cb = new HandlerCallBack (AssimpCallBack);
   SetProgressHandlerCallBack (cb);
}

but I'm getting an exception, 但我得到一个例外,

SetProgressHandlerCallBack SetProgressHandlerCallBack

at (wrapper managed-to-native) ModellInstantiator:SetProgressHandlerCallBack (ModellInstantiator/HandlerCallBack) at(wrapper managed-to-native)ModellInstantiator:SetProgressHandlerCallBack(ModellInstantiator / HandlerCallBack)

and I cant figure out what am I missing. 我无法弄清楚我错过了什么。

In your code above the SetProgressHandlerCallback function you show looks like this: 在您上面的代码中,您显示的SetProgressHandlerCallback函数如下所示:

void Importer::SetProgressHandlerCallBack(...) { ... }

There are 2 problems with this, both of which can be explained with a simple Minimum Complete Verifiable Example, I created 1 a new Visual Studio solution, containing a C# (WinForms) project and a C++ Dll (unmanaged not C++/CLI). 有2个问题与此,这两者都可以用简单的最小完全可验证实施例进行说明,我创建1一个新的Visual Studio解决方案,将含有C#(的WinForms)项目和一个C ++ DLL(非托管不C ++ / CLI)。

In the DLL (dllmain.cpp) I placed the following code: 在DLL(dllmain.cpp)中,我放置了以下代码:

typedef void (__stdcall *HandlerCallBack)(float);

extern "C" {

    // extern "C" ignored for C++ classes
    class __declspec(dllexport) TestClass
    {
    public:
        static void CallMeBack(HandlerCallBack callback)
        {
            callback(1.0f);
        }
    };


    void __declspec(dllexport) CallRightBack(HandlerCallBack callback)
    {
        TestClass::CallMeBack(callback);
    }
}

You can see the callback signature matching the one you're using, and a static class method and a exported function. 您可以看到与您正在使用的回调签名匹配的回调签名,以及静态类方法和导出的函数。 Build this, start the Visual Studio command prompt and run 构建它,启动Visual Studio命令提示符并运行

dumpbin /exports <dllname>.dll

This gives you the exported functions from the DLL, which looks something like this: 这为您提供了DLL中的导出函数,如下所示:

(Trimmed to just show what we care about)
    ordinal hint RVA      name

          1    0 00011082 ??4TestClass@@QEAAAEAV0@$$QEAV0@@Z = @ILT+125(??4TestClass@@QEAAAEAV0@$$QEAV0@@Z)
          2    1 000110E1 ??4TestClass@@QEAAAEAV0@AEBV0@@Z = @ILT+220(??4TestClass@@QEAAAEAV0@AEBV0@@Z)
          3    2 00011069 ?CallMeBack@TestClass@@SAXP6AXM@Z@Z = @ILT+100(?CallMeBack@TestClass@@SAXP6AXM@Z@Z)
          4    3 00011014 CallRightBack = @ILT+15(CallRightBack)

You'll notice that the regular global function is exported with its undecorated name, but that the static method is exported with a decorated (mangled) name. 您会注意到常规全局函数是以未修饰的名称导出的,但静态方法是使用修饰(受损)名称导出的。

Now lets add some code to the C# project and see why this becomes a problem. 现在让我们为C#项目添加一些代码,看看为什么这会成为一个问题。 Add 2 buttons (button1 and button2 2 ). 添加2个按钮(button1和button2 2 )。 To the form, I added the following code: 在表单中,我添加了以下代码:

[UnmanagedFunctionPointer(CallingConvention.StdCall)]
delegate void HandlerCallbackDelegate(float value);

[DllImport("CppDllTestProj.dll")]
static extern void CallRightBack([MarshalAs(UnmanagedType.FunctionPtr)]HandlerCallbackDelegate callback);

[DllImport("CppDllTestProj.dll")]
static extern void CallMeBack([MarshalAs(UnmanagedType.FunctionPtr)]HandlerCallbackDelegate callback);

HandlerCallbackDelegate callbackDel;

// in the designer associated with button1
private void button1_Click(object sender, EventArgs e)
{
    if (this.callbackDel == null)
    {
        this.callbackDel = new HandlerCallbackDelegate(this.Callback);
    }
    CallRightBack(callbackDel);
}

// in the designer associated with button2
private void button2_Click(object sender, EventArgs e)
{
    if (this.callbackDel == null)
    {
        this.callbackDel = new HandlerCallbackDelegate(this.Callback);
    }
    CallMeBack(callbackDel);
}

void Callback(float value)
{
    MessageBox.Show(value.ToString());
}

Compile, copy the dll into the C# project's build directory, and run. 编译,将dll复制到C#项目的构建目录中,然后运行。 Click button1, the callback is called, and the message box shows up. 单击button1,调用回调,并显示消息框。 Click button 2 and the program crashes with the exception: 单击按钮2,程序崩溃,但异常:

Unable to find an entry point named 'CallMeBack' in DLL 'CppDllTestProj.dll'. 无法在DLL“CppDllTestProj.dll”中找到名为“CallMeBack”的入口点。 at ScratchApp.Form1.CallMeBack(HandlerCallbackDelegate callback) at ScratchApp.Form1.button2_Click(Object sender, EventArgs e) in Form1.cs:line 49 在Form1.cs中ScratchApp.Form1.button2_Click(Object sender,EventArgs e)的ScratchApp.Form1.CallMeBack(HandlerCallbackDelegate回调):第49行

Unable to find an entry point named 'CallMeBack' means that it couldn't find a function in that DLL with that name. 无法找到名为“CallMeBack”的入口点意味着它无法在该DLL中找到具有该名称的函数。 If I now change the CallMeBack definition in the C# test application to: 如果我现在将C#测试应用程序中的CallMeBack定义更改为:

[DllImport("CppDllTestProj.dll", EntryPoint="?CallMeBack@TestClass@@SAXP6AXM@Z@Z")]
static extern void CallMeBack([MarshalAs(UnmanagedType.FunctionPtr)]HandlerCallbackDelegate callback);

Recompile, and restart, now both buttons function correctly. 重新编译并重新启动,现在两个按钮都能正常工作。 (Your mangled/decorated name may look different. Use whatever value you get from dumpbin.) (你的受损/装饰名称可能看起来不同。使用从dumpbin获得的任何值。)

The root of this problem is that the extern "c" storage class specifier is ignored for C++ classes and class members 3 . 这个问题的根源是C ++类和类成员3忽略了extern "c"存储类说明符。

The other problem which you will have as soon as you fix the above, is this code: 修复上述内容后,您将遇到的另一个问题是此代码:

void SomeFunction () {
   HandlerCallBack cb = new HandlerCallBack (AssimpCallBack);
   SetProgressHandlerCallBack (cb);
}

You'll note that cb becomes available for garbage collection the instant that control returns from the call to SetProgressHandlerCallBack . 您将注意到,当控件从对SetProgressHandlerCallBack的调用返回时, cb变为可用于垃圾收集。 Once that delegate is garbage collected any callback will fail. 一旦该委托被垃圾收集,任何回调都将失败。 Spectacularly. 壮观。


1 Technically the same project I use for all testing, but I clear the code each time. 1从技术上讲,我用于所有测试的项目相同,但每次都清除代码。
2 Creative names, I know. 我知道2个有创意的名字。
3 Source: Is it possible to export a C++ member method with C linkage in a DLL? 3来源: 是否可以在DLL中导出C链接的C ++成员方法?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM