受欢迎的博客标签

C++调用C# dll-通过CLR API实现

Published

step 1:c#生成dll

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace ClassLibrary1
{
    public class Class1
    {
        public static int EntryPoint(string arg)
        {
            File.AppendAllText("C:/xx.txt", "qweqwe");
            return 0;
        }
    }
}

 

step 2:C++

//Reference From GitHub entice:https://github.com/entice/client/blob/42f388d68b1954ef244c379560eeb4867ae80b7e/Loader/Loader/DllMain.cpp

#include <Windows.h>
#include <stdio.h>
#include <iostream>
#include <mscoree.h>
#include <metahost.h>
#include <assert.h>

#pragma comment(lib, "mscoree.lib")

#define BUFFER_SIZE 500
#include "stdafx.h"


void StartTheDotNetRuntime(LPCWSTR runtimeVersion, LPCWSTR dllPath, LPCWSTR startClass, LPCWSTR startMethod, LPCWSTR startArgument)
{
    ICLRMetaHost *pMetaHost = NULL;
    ICLRMetaHostPolicy *pMetaHostPolicy = NULL;
    ICLRDebugging *pCLRDebugging = NULL;

    CLRCreateInstance(CLSID_CLRMetaHost, IID_ICLRMetaHost, (LPVOID*)&pMetaHost);
    CLRCreateInstance(CLSID_CLRMetaHostPolicy, IID_ICLRMetaHostPolicy, (LPVOID*)&pMetaHostPolicy);
    CLRCreateInstance(CLSID_CLRDebugging, IID_ICLRDebugging, (LPVOID*)&pCLRDebugging);

    DWORD dwVersion = 0;
    DWORD dwImageVersion = 0;
    ICLRRuntimeInfo *pRuntimeInfo;
    HRESULT result;
    result = pMetaHost->GetRuntime(runtimeVersion, IID_ICLRRuntimeInfo, (LPVOID*)&pRuntimeInfo);
    assert(SUCCEEDED(result));

    ICLRRuntimeHost * pRuntimeHost = NULL;
    result = pRuntimeInfo->GetInterface(CLSID_CLRRuntimeHost, IID_ICLRRuntimeHost, (LPVOID*)&pRuntimeHost);
    assert(SUCCEEDED(result));

    result = pRuntimeHost->Start();
    assert(SUCCEEDED(result));

    DWORD dwRetCode = 0;
    result = pRuntimeHost->ExecuteInDefaultAppDomain(dllPath, startClass, startMethod, startArgument, &dwRetCode);
    assert(SUCCEEDED(result));
    pRuntimeHost->Stop();
    pRuntimeHost->Release();
    pRuntimeInfo->Release();
    pCLRDebugging->Release();
    pMetaHostPolicy->Release();
    pMetaHost->Release();
}

void Loader()
{
    wchar_t* runtimeVersionSpace = new wchar_t[BUFFER_SIZE];
    wchar_t* dllPathSpace = new wchar_t[BUFFER_SIZE];
    wchar_t* currentDir = new wchar_t[BUFFER_SIZE];

    GetCurrentDirectoryW(BUFFER_SIZE, currentDir);

    StartTheDotNetRuntime(L"v4.0.30319", L"ClassLibrary1.dll", L"ClassLibrary1.Class1", L"EntryPoint", L"");

    free(runtimeVersionSpace);
    free(dllPathSpace);
    free(currentDir);
}


int _tmain(int argc, _TCHAR* argv[])
{
    HANDLE handle = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)Loader, NULL, 0, NULL);

    for (size_t i = 0; i < 10; i++)
    {
        Sleep(100);
    }

    TerminateThread(handle, 0);

    return 0;
}

step 3:

然后把c#生成的dll,放到c++的build目录下,再以管理员权限执行即可。

最后会在c盘根目录下创建一个xx.txt文件。说明调用C#成功。