.net - 将托管 DLL 注入(inject) .net 4.0 应用程序

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

我已经使用引导加载程序 dll(在 c++ 中)成功地将托管 DLL 注入(inject)到 .net 3.5 应用程序中,然后在(c#)中使用我的“有效负载”dll。

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

引导加载程序 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();
    }

有效负载 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); 

最佳答案

.NET 4.0 更改了接口(interface)。而不是使用 CorBindToRuntimeEx您应该使用新的 ICLRMetaHost interface .

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

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();

关于.net - 将托管 DLL 注入(inject) .net 4.0 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7278192/

相关文章:

.net - Windows 服务如何以编程方式自行重启?

c# - 为什么我可以检查 DateTime 是否为 null,即使它是一个值类型?

java - 如何为 Java 应用程序调试 C++ dll

c# - 如何从 VB.Net 调用 C# 类的静态方法?

.net - 如何在单独的线程中运行方法

c# - 检查所选日期是否在预定义假期的三天内

.net - 将非托管 DLL 部署到输出目录

c# - 将 OwinHttpRequestContext 转换为 HttpContext? (IHttpHandler 和 websockets)

.net - 移植到 VS2015/.NET 4.6 后,C++/CLI DLL 在加载时崩溃

c# - 什么时候创建变量?