// ConsoleApplication1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
// #include "pch.h"
#include <iostream>
#include <metahost.h>
#include <atlbase.h>
#include <atlcom.h> #pragma comment(lib, "mscoree.lib") #define IfFailRet(expr) { hr = (expr); if(FAILED(hr)) return (hr); }
#define IfNullFail(expr) { if (!expr) return (E_FAIL); } extern "C" int __declspec(dllexport) CALLBACK CallClrMethod(
const WCHAR *miniRuntimeVersion,
const WCHAR *assemblyName,
const WCHAR *typeName,
const WCHAR *methodName,
const WCHAR *args,
LPDWORD pdwResult
)
{
int hr = S_OK;
CComPtr<ICLRMetaHost> spHost;
hr = CLRCreateInstance(CLSID_CLRMetaHost, IID_PPV_ARGS(&spHost));
CComPtr<ICLRRuntimeInfo> spRuntimeInfo;
CComPtr<IEnumUnknown> pRunTimes;
IfFailRet(spHost->EnumerateInstalledRuntimes(&pRunTimes));
ICLRRuntimeInfo *pUnkRuntime = NULL;
ULONG fetched = ;
wchar_t version[];
DWORD versionStringSize = ;
while (S_OK == pRunTimes->Next(, (IUnknown **)&pUnkRuntime, &fetched))
{
if (fetched <= || pUnkRuntime == nullptr)
break; hr = pUnkRuntime->GetVersionString(version, &versionStringSize); if (versionStringSize >=
&& (int)version[] >= (int)miniRuntimeVersion[]
&& (int)version[] >= (int)miniRuntimeVersion[]
&& (int)version[] >= (int)miniRuntimeVersion[]) {
CComQIPtr<ICLRRuntimeInfo> pp(pUnkRuntime);
spRuntimeInfo = pp;
break;
}
} IfNullFail(spRuntimeInfo); BOOL bStarted;
DWORD dwStartupFlags;
hr = spRuntimeInfo->IsStarted(&bStarted, &dwStartupFlags); CComPtr<ICLRRuntimeHost> spRuntimeHost;
IfFailRet(spRuntimeInfo->GetInterface(CLSID_CLRRuntimeHost, IID_PPV_ARGS(&spRuntimeHost)));
if (!bStarted)
hr = spRuntimeHost->Start();
hr = spRuntimeHost->ExecuteInDefaultAppDomain(
assemblyName,
typeName,
methodName,
args,
pdwResult); return hr;
} int main()
{
DWORD dwResult;
HRESULT hr = CallClrMethod(
L"4.0",
L"ClassLibrary1.dll", // name of DLL (can be fullpath)
L"ClassLibrary1.Class1", // name of managed type
L"ManagedMethodCalledFromExtension", // name of static method
L"some args xx",
&dwResult); return ;
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace ClassLibrary1
{
public class Class1
{
/// <summary>
/// a managed static method that gets called from native code
/// </summary>
public static int ManagedMethodCalledFromExtension(string args)
{
// need to return an integer: the length of the args string
return args.Length * ;
} }
}

此项目加入了Reactor加壳保护,在编译后事件中添加命令:

"C:\Program Files (x86)\Eziriz\.NET Reactor\dotNET_Reactor.Console.exe" -file "$(TargetPath)" -targetfile "<AssemblyLocation>\<AssemblyFileName>"

05-22 01:19