CAD工具之家's Archivers

From boitboy on 2013-07-09 20:28:35

C++逆向访问DotNet方法(不借助COM)

使用DllImport可以在DotNet中访问C++的一些导出函数,可能有非常多的人会,但是如何在C++中访问DotNet呢(不借助COM)? 使用下面的代码就可以了 //作者:boitboy //个人博客:http://www.cadgj.com //功能:C++访问DotNet方法 //最后修改时间:2012/7/2 #include "StdAfx.h" #include "DotNetFunction.h" #include "mscoree.h" #include "corerror.h" #include "stdio.h" #include "string.h" #include <atlconv.h> //功能:在默认的DotNet应用程序域中调用DotNet方法 //参数:strAssemblyPath,DotNet DLL或EXE文件名称 //     strTypeName,类型名称,包括命名空间(要求为静态类) //     strMethodName,方法名称,要求为静态方法,有且只有一个类型为string的参数, 返回值为一个Int类型 //     strArgument,参数 //返回值:执行结果 int ExecuteInDefaultAppDomain(const LPWSTR strAssemblyPath,          const LPWSTR strTypeName,          const LPWSTR strMethodName,          const LPWSTR strArgument) {  try  {   ICLRControl *clrcontrol=NULL;   //CLR运行时宿主   ICLRRuntimeHost * clr=NULL;   LPVOID clrptr;   HRESULT res;   DWORD value=0;   //加载DotNet框架   res=CorBindToRuntimeEx(L"v2.0.50727",L"svr",    //启动编译优化    STARTUP_LOADER_OPTIMIZATION_MASK|    //启动多线程GC(垃圾回收器)    STARTUP_CONCURRENT_GC|    //所有程序集归属单个应用程序域(非共享)    STARTUP_LOADER_OPTIMIZATION_SINGLE_DOMAIN,    CLSID_CLRRuntimeHost,    IID_ICLRRuntimeHost,&clrptr);   clr=(ICLRRuntimeHost*)clrptr;   clr->GetCLRControl(&clrcontrol);   //设置CLR应用程序域控制器   res=clrcontrol->SetAppDomainManagerType(L"mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",L"System.AppDomain");   res=clr->Start();//启动CLR(所有对CLR的设置都必须在启动前进行)   //在默认应用程序域中执行函数(参数1 类库文件路径 参数2 类型完全限定名(包含命名空间) 参数3 方法名称(静态方法) 参数4 方法的参数) 注意:方法必须返回一个Int类型 参数是一个String类型   res=clr->ExecuteInDefaultAppDomain(    //参数1 类库文件路径    strAssemblyPath,    //参数2 类型完全限定名(包含命名空间)    strTypeName,    //参数3 方法名称(静态方法)    strMethodName,    //参数4 方法的参数    strArgument,    &value);   if(FAILED(res))   {    WCHAR strInfo[4096]={0};    swprintf(strInfo,L"执行DotNet方法失败HRESULT=%x。AssemblyPath=%s;TypeName=%s;MethodName=%s;Argument=%s",res,strAssemblyPath,strTypeName,strMethodName,strArgument);    OutputDebugStringW(strInfo);    return -1;   }   return value;  }  catch(...)  {   WCHAR strInfo[4096]={0};   swprintf(strInfo,L"执行DotNet方法发生异常。AssemblyPath=%s;TypeName=%s;MethodName=%s;Argument=%s",strAssemblyPath,strTypeName,strMethodName,strArgument);   OutputDebugStringW(strInfo);   return -1;  } } 下载测试工程:DotNetExchange

查看完整版本: C++逆向访问DotNet方法(不借助COM)

Tags: C++, COM, DotNet, 逆向访问


©CAD工具之家
创办于:2013年5月24日