我目前正在尝试从非托管C++应用程序中调用C#DLL中的函数.
在网上搜索了几个小时后,我发现我有几个选择.
我可以使用COM,DllExport或者使用反向PInvoke和委托.最后听起来对我最有吸引力,所以在搜索之后我就到了这里.
它声明该文章展示了如何使用反向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);
}
Run Code Online (Sandbox Code Playgroud)
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);
}
}
Run Code Online (Sandbox Code Playgroud)
Jer*_*all 10
嗯,只需启动你自己的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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5619 次 |
| 最近记录: |