我目前正在尝试从非托管 C++ 应用的 C# DLL 调用函数。
在网上搜索了几个小时之后,我发现我有几个选择。
我可以使用 COM、DllExport
,或对委托(delegate)使用反向 PInvoke。最后一个听起来对我最有吸引力,所以在搜索 SO 之后我结束了 here .
它指出文章展示了如何使用反向 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:%x\n", 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:%x\n", hr);
hr = pHost->Stop();
printf("HRESULT:%x\n", hr);
pHost->Release();
}
int main()
{
Bootstrap();
}
关于c# - 从 native C++ 反向调用 PInvoke,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14257428/