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

非托管C++访问 C#编写的DLL (备忘)

2010-11-30 16:16 253 查看
整理:

  对于使用 .NET Framework 编写的App,装载CLR是完全透明的。如果将托管代码编译为 .exe程序,则在运行 .exe 时,mscoree.dll 会自动启动运行时。但是,非托管应用程序也可通过装载CLR受益。运行时为扩展应用程序(如 Microsoft IIS 和 Microsoft SQL Server 2005)提供了框架。

  .NET Framework App无论是通过托管 .exe 程序集自动调用的,还是使用非托管宿主 API 加载的,都需要一段称为运行时主机的代码。运行时主机会将运行时加载到进程中,在进程中创建应用程序域,然后在这些应用程序域内加载和执行用户代码。

  

#include <mscoree.h>
#pragma comment(lib,"mscoree.lib")

void CTestInvokeCSdllDlg::OnBnClickedButton1()
{
  // TODO: Add your control notification handler code here
  ICLRRuntimeHost *pClrHost;
  HRESULT hr = CorBindToRuntimeEx(NULL,
    NULL,0,
    CLSID_CLRRuntimeHost,
    IID_ICLRRuntimeHost,
    (PVOID*)&pClrHost);

  //对于 1.0 和 1.1 版本,请使用 CLSID_CorRuntimeHost 和 IID_ICorRuntimeHost 来获取 ICorRuntimeHost 接口。

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

  hr = pClrHost->ExecuteInDefaultAppDomain(L"SPWSInvokeDll.dll",L"SPWSInvokeDll.Class1",L"TestMethod",
    L"TestStringParam",&retVal);

   CString strRetVal;
  strRetVal.Format(L"%d", retVal);

  if(S_OK==hr)
    AfxMessageBox(strRetVal);
  else
    AfxMessageBox(L"error");
}

这里有个缺陷,似乎不能将CLR unload,ICLRRuntimeHost提供的stop函数没有解决任何问题——参考(2)。

参考:

(1) http://msdn.microsoft.com/zh-cn/vstudio/9x0wh2z3(VS.90).aspx

(2) http://social.msdn.microsoft.com/Forums/en-NZ/netfxtoolsdev/thread/3e51f21e-ee4b-4a72-812e-ef6b4c3bb0dc
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: