编写自定义 .NET Core 主机以从本机代码控制 .NET 运行时,第二种方法(代码)

#include "stdafx.h"

#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include<Windows.h>

#include "coreclrhost.h"


void BuildTpaList(const char* directory, const char* extension, std::string& tpaList);
typedef char* doWork_ptr(char *argv);
doWork_ptr managedDelegate;
int main()
{
    coreclr_initialize_ptr initializeCoreClr = (coreclr_initialize_ptr)GetProcAddress(coreClr, "coreclr_initialize");
    coreclr_create_delegate_ptr createManagedDelegate = (coreclr_create_delegate_ptr)GetProcAddress(coreClr, "coreclr_create_delegate");
    coreclr_shutdown_ptr shutdownCoreClr = (coreclr_shutdown_ptr)GetProcAddress(coreClr, "coreclr_shutdown");
    coreclr_execute_assembly_ptr executeAssembly = (coreclr_execute_assembly_ptr)GetProcAddress(coreClr, "coreclr_execute_assembly");

    std::string tpaList;
    BuildTpaList(runtimePath, ".dll", tpaList);

    const char* propertyKeys[] = {
        "TRUSTED_PLATFORM_ASSEMBLIES"      // Trusted assemblies
    };
    const char* propertyValues[] = {
        tpaList.c_str()
    };

    void* hostHandle;
    unsigned int domainId;

    // This function both starts the .NET Core runtime and creates
    // the default (and only) AppDomain
    int hr = initializeCoreClr(
        runtimePath,        // App base path
        "SampleHost",       // AppDomain friendly name
        sizeof(propertyKeys) / sizeof(char*),   // Property count
        propertyKeys,       // Property names
        propertyValues,     // Property values
        &hostHandle,        // Host handle
        &domainId);         // AppDomain ID


    //hr = createManagedDelegate(
    //    hostHandle,
    //    domainId,
    //    "Main, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
    //    "Main.Program",
    //    "ABC",
    //    (void**)&managedDelegate);

    const char *ccp= "abcdef";
    unsigned int *exitCode;
    hr = executeAssembly(
        hostHandle,
        domainId,
        1,
        &ccp,
        "Main.exe",
        (unsigned int*)&exitCode);

    return 0;
}

void BuildTpaList(const char* directory, const char* extension, std::string& tpaList)
{
    std::string searchPath(directory);
    searchPath.append("\\");
    searchPath.append("*");
    searchPath.append(extension);

    WIN32_FIND_DATAA findData;
    HANDLE fileHandle = FindFirstFileA(searchPath.c_str(), &findData);

    if (fileHandle != INVALID_HANDLE_VALUE)
    {
        do
        {
            tpaList.append(directory);
            tpaList.append("\\");
            tpaList.append(findData.cFileName);
            tpaList.append(";");

        } while (FindNextFileA(fileHandle, &findData));
        FindClose(fileHandle);
    }
}

猜你喜欢

转载自blog.csdn.net/tangyanzhi1111/article/details/88642892