您的位置:首页 > 编程语言 > C#

非托管C++代码调用C#编写的dll方法

2010-06-04 11:17 826 查看
非托管C++代码调用C#编写的dll方法

CLR VIA C#这本书里面的内容,在网上好像很少关于这方面的内容,贴出来以后留着看。

C#调用C++编写的dll,一般都是直接用dllimport,这个资料很多。C++调用C#编写的dll,一般方法都是先用托管C++将C#的dll进行一次封装,然后由非托管C++调用封装好的dll。

CLR VIA C#在讲寄宿和应用程序域的内容时,提供了一个非托管C++直接调用的方法。原理就是,在非托管代码中手动启动CLR加载应用程序域来运行托管的dll,从而调用其中的方法。

代码如下:

#include <Windows.h>
#include <MSCorEE.h>
#include <stdio.h>
#pragma comment(lib,"mscoree.lib")
int _tmain(int argc, _TCHAR* argv[])
{
ICLRRuntimeHost *pClrHost;
HRESULT hr = CorBindToRuntimeEx(NULL,

NULL,0,

CLSID_CLRRuntimeHost,

IID_ICLRRuntimeHost,

(PVOID*)&pClrHost);

//启动CLR
pClrHost->Start();
DWORD retVal=0;

//将dll加载到默认应用程序域中,并调用其中的方法
hr = pClrHost->ExecuteInDefaultAppDomain(L"test.dll",L"test.MyType",L"TestMethod",
L"TestStringParam",&retVal);
if(S_OK==hr)
wprintf(L"Managed code returned %d/n",retVal);
else
wprintf(L"failed to call csharp dll./n");
getchar();
return 0;
}

C#编写的test.dll如下:

namespace test
{
class MyType
{
public static Int32 TestMethod(String s)
{
Console.WriteLine("Managed assembly: {0}",s);
return s.Length;
}
}

}

代码输出:

Managed assembly: TestStringParam
Managed code returned 15

可以看到c++成功调用了test.DLL中的方法,并且可以传入参数和接收返回值。

想深入的了解,可以看下面的内容:

http://msdn.microsoft.com/zh-cn/vstudio/9x0wh2z3.aspx
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: