将托管DLL注入.net 4.0应用程序

时间:2011-09-02 00:43:43

标签: .net dll c#-4.0 code-injection

我已经成功地使用bootloader dll(在c ++中)将托管DLL注入到.net 3.5应用程序中,然后在(c#)中将我的“payload”dll注入。

当我尝试对.net 4.0应用程序执行此操作总是崩溃。

Bootloader C ++:

    #include "MSCorEE.h"

    void StartTheDotNetRuntime()
    {
        // Bind to the CLR runtime..
        ICLRRuntimeHost *pClrHost = NULL;
        HRESULT hr = CorBindToRuntimeEx(
        NULL, L"wks", 0, CLSID_CLRRuntimeHost,
        IID_ICLRRuntimeHost, (PVOID*)&pClrHost);

        hr = pClrHost->Start();

        // Okay, the CLR is up and running in this (previously native) process.
        // Now call a method on our managed C# class library.
        DWORD dwRet = 0;
        hr = pClrHost->ExecuteInDefaultAppDomain(
             L"payload.dll",
             L"MyNamespace.MyClass", L"MyMethod", L"MyParameter", &dwRet);

        // Optionally stop the CLR runtime (we could also leave it running)
        hr = pClrHost->Stop();

       // Don't forget to clean up.
       pClrHost->Release();
    }

Payload C#:

    using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Windows.Forms;

    namespace MyNamespace
    {
       public class MyClass
       {
          // This method will be called by native code inside the target process...
          public static int MyMethod(String pwzArgument)
         {
             MessageBox.Show("Hello World");
             return 0;
         }

       }
    }

我尝试使用以下修复程序,但无济于事,任何想法? 固定 - :

  hr = pMetaHost->GetRuntime(L"v4.0.30319", IID_ICLRRuntimeInfo, (LPVOID*)&lpRuntimeInfo); 

2 个答案:

答案 0 :(得分:11)

接口随.NET 4.0改变。您应该使用新的CorBindToRuntimeEx interface

,而不是使用ICLRMetaHost

代码可能如下所示(没有错误检查):

ICLRMetaHost *pMetaHost = NULL;
CLRCreateInstance(CLSID_CLRMetaHost, IID_ICLRMetaHost, (LPVOID*)&pMetaHost);

ICLRRuntimeInfo *pRuntimeInfo = NULL;
pMetaHost->GetRuntime(L"v4.0.30319", IID_ICLRRuntimeInfo, (LPVOID*)&pRuntimeInfo);

ICLRRuntimeHost *pClrRuntimeHost = NULL;
pRuntimeInfo->GetInterface(CLSID_CLRRuntimeHost, IID_ICLRRuntimeHost, (LPVOID*)&pClrRuntimeHost);

pClrRuntimeHost->Start();

答案 1 :(得分:4)

我看到你的代码有几个“怪癖” - 比如CorBindToRuntimeEx是根据MS不推荐使用的.NET 4。

.NET 4运行时首次提供了将多个运行时版本并排加载到同一进程中的能力,因此我怀疑MS必须进行一些更改。到CLR托管以实现这一目标......

您可以找到推荐的新界面here