微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

CLR 主机 - 如何使用任意方法签名执行函数

如何解决CLR 主机 - 如何使用任意方法签名执行函数

我有一个托管 C# 测试 DLL,我想从我的非托管 C++ 代码调用它的函数

问题是我找不到显示如何从我的 c++ 代码调用任意函数的示例,我只能让 ICLRRuntimeHost::ExecuteInDefaultAppDomain 工作,但该函数确实使用了预定义的方法签名。>

问题

我可以从我的 C# DLL 中执行 ShowMsg 函数,但我不知道如何使用除 int(int) 之外的其他签名调用方法。有人可以帮我吗?

C++ 代码

// interface deFinitions of functions from c# dll
typedef int (*TestCallbackPtr)(std::wstring info,int value1,double value2);
typedef int (*TestFunctionPtr)(std::wstring string1,int int1,double double1,TestCallbackPtr callback);

// path of my c# dll
auto pathDll = L"..." 

void Runtest()
{
    ICLRMetaHost* clrMetaHost = NULL;
    ICLRRuntimeInfo* clrRuntimeInfo = NULL;
    ICLRRuntimeHost* clrRuntimeHost = NULL;
    
    // loading the data above is excluded for simplicity!
    // ... 
    
    // -------------
    // Test 1: run ShowMsg => WORKING
    // -------------
    
    DWORD pReturnValue;
    HRESULT result = clrRuntimeHost->ExecuteInDefaultAppDomain(pathDll,L"Test.Managed",L"ShowMsg",L"Hello from C++",&pReturnValue);
    
    // -------------
    // Test 2: run TestFunction
    // -------------
    
    TestCallbackPtr callback = [](std::wstring info,double value2) {
        return 21;
    };
    TestFunctionPtr function = NULL;
    
    // how to continue? how can I execute the function here and assign my local function pointer so that following will work:
    // (*function)(L"Test",45,1.23,callback);
}

C# 代码

namespace Test
{    
    public class Managed
    {
        public static int ShowMsg(string msg)
        {
            MessageBox.Show(msg);
            return 0;
        }

        public delegate int TestCallback([MarshalAs(UnmanagedType.LPWStr)] string info,double value2);

        public static int TestFunction(
            [MarshalAs(UnmanagedType.LPWStr)] string string1,TestCallback callback)
        {
            string info = $"string1 = {string1} | int1 = {int1} | double1 = {double1}";
            int returnValue = callback(info,5,10.34);
            return returnValue;
        }
    }   
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。