在C#参数中使用回调函数封送C/C++函数

我的本机代码中包含以下内容:

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

我需要打电话

SetProgressHandlerCallBack (HandlerCallBack CallBack)

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

但我得到一个例外,

SetProgressHandlerCallBack

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

我无法弄清楚我错过了什么.

最佳答案 在您上面的代码中,您显示的SetProgressHandlerCallback函数如下所示:

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

这有两个问题,这两个问题都可以用一个简单的最小完整可验证示例来解释,我创建了一个新的Visual Studio解决方案,包含一个C#(WinForms)项目和一个C Dll(非托管而不是C/C++LI).

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

您可以看到与您正在使用的回调签名匹配的回调签名,以及静态类方法和导出的函数.构建它,启动Visual Studio命令提示符并运行

dumpbin /exports <dllname>.dll

这为您提供了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)

您会注意到常规全局函数是以未修饰的名称导出的,但静态方法是使用修饰(受损)名称导出的.

现在让我们为C#项目添加一些代码,看看为什么这会成为一个问题.添加2个按钮(button1和button22).在表单中,我添加了以下代码:

[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());
}

编译,将dll复制到C#项目的构建目录中,然后运行.单击button1,调用回调,并显示消息框.单击按钮2,程序崩溃,但异常:

Unable to find an entry point named ‘CallMeBack’ in DLL ‘CppDllTestProj.dll’.
at ScratchApp.Form1.CallMeBack(HandlerCallbackDelegate callback)
at ScratchApp.Form1.button2_Click(Object sender, EventArgs e) in Form1.cs:line 49

无法找到名为“CallMeBack”的入口点意味着它无法在该DLL中找到具有该名称的函数.如果我现在将C#测试应用程序中的CallMeBack定义更改为:

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

重新编译并重新启动,现在两个按钮都能正常工作. (你的受损/装饰名称可能看起来不同.使用从dumpbin获得的任何值.)

这个问题的根源是C类和类成员3忽略了extern“c”存储类说明符.

修复上述内容后,您将遇到的另一个问题是此代码:

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

您将注意到,当控件从对SetProgressHandlerCallBack的调用返回时,cb变为可用于垃圾收集.一旦该委托被垃圾收集,任何回调都将失败.壮观.

1技术上我用于所有测试的项目相同,但我每次都清除代码.
我知道,有两个名字.
3Source:Is it possible to export a C++ member method with C linkage in a DLL?

点赞