从本地c++中反向PInvoke

Reverse PInvoke from native C++

本文关键字:PInvoke c++      更新时间:2023-10-16

我正在尝试从一个非托管的c++应用程序从c# DLL调用一个函数。

在网上搜索了几个小时之后,我发现我有几个选择。

我可以使用COM, DllExport,或者对委托使用反向的PInvoke。最后一个听起来最吸引我,所以在搜索了so之后,我在这里结束了。

它指出本文展示了如何使用反向PInvoke,但看起来c#代码必须首先导入c++ Dll,然后才能使用它。

我需要能够使用c++来调用我的c# Dll函数,而无需首先运行c#应用程序。

也许反向PInvoke不是这样做的,但是当涉及到低级别的东西时,我相当缺乏经验,所以任何关于如何做到这一点的指针或提示都将是伟大的。

链接中的代码是

c#

using System.Runtime.InteropServices;
public class foo    
{    
    public delegate void callback(string str);
    public static void callee(string str)    
    {    
        System.Console.WriteLine("Managed: " +str);    
    }
    public static int Main()    
    {    
        caller("Hello World!", 10, new callback(foo.callee));    
        return 0;    
    }
    [DllImport("nat.dll",CallingConvention=CallingConvention.StdCall)]    
    public static extern void caller(string str, int count, callback call);    
}

c++

#include <stdio.h>    
#include <string.h>
typedef void (__stdcall *callback)(wchar_t * str);    
extern "C" __declspec(dllexport) void __stdcall caller(wchar_t * input, int count, callback call)    
{    
    for(int i = 0; i < count; i++)    
    {    
        call(input);    
    }    
}

嗯,只要启动你自己的CLR主机并运行你需要的:

#include <mscoree.h>
#include <stdio.h>
#pragma comment(lib, "mscoree.lib") 
void Bootstrap()
{
    ICLRRuntimeHost *pHost = NULL;
    HRESULT hr = CorBindToRuntimeEx(L"v4.0.30319", L"wks", 0, CLSID_CLRRuntimeHost, IID_ICLRRuntimeHost, (PVOID*)&pHost);
    pHost->Start();
    printf("HRESULT:%xn", hr);
    // target method MUST be static int method(string arg)
    DWORD dwRet = 0;
    hr = pHost->ExecuteInDefaultAppDomain(L"c:\temp\test.dll", L"Test.Hello", L"SayHello", L"Person!", &dwRet);
    printf("HRESULT:%xn", hr);
    hr = pHost->Stop();
    printf("HRESULT:%xn", hr);
    pHost->Release();
}
int main()
{
    Bootstrap();
}