C:\Program Files\dotnet\host\fxr在这个目录下面是你的当前电脑安装的.Net 版本了。比如7.0.0或者其它版本,它是一个文件夹,它的路径看起来是这样:
C:\Program Files\dotnet\host\fxr\7.0.0这个路径下面有一个hostfxr.dll文件,记住它,后面要用。
internal class Program { static void Main(string[] args) { Console.WriteLine("Hello, World!"); Console.ReadLine(); } }把它编译之后,找到它的路径。
Host_Path=E:\Visual Studio Project\Test\Test\bin\Debug\net6.0APP路径,也就是的程序编译之后的DLL路径,本例如下:
ConsoleApp=\Visual Studio Project\Test\Test\bin\Debug\net6.0\Test.dll.Net根目录路径:
DotNet_Root=C:\Program Files\dotnet\shared\Microsoft.NETCore.App\6.0.8OK,假如你以上三样准备好了,我们继续下面的步骤。
#include <stdio.h> #include <Windows.h> #include "hostfxr.h" hostfxr_main_startupinfo_fn startupinfo_fptr;// 实例化一个运行时入口函数指针,此指针用以调用了.Net 托管代码里面的Main函数入口 int main(int argc, char** argv) { // 堆代码 www.duidaima.com // 这个就是上面的Host_Path路径。注意CPP里面的路径是双斜杠 const wchar_t* Host_Path = L"E:\\Visual Studio Project\\Test\\Test\\bin\\Debug\\net6.0"; //这个就是上面的ConsoleApp const wchar_t* ConsoleApp = L"E:\\Visual Studio Project\\Test\\Test\\bin\\Debug\\net6.0\\Test.dll";//这个是上面的AppConsole路径。 //这个呢,就是上面的DotNet_Root路径。 const wchar_t* DotNet_Root = L"C:\\Program Files\\dotnet\\shared\\Microsoft.NETCore.App\\7.0.0"; //这里的argvV参数区别于Main的argv参数,主要用于运行时入口函数指针的参数。 const wchar_t* argvV = L""; //用LoadLibraryExA加载上面前期准备的步骤里的hostfxr.dll HMODULE h = LoadLibraryExA("C:\\Program Files\\dotnet\\host\\fxr\\7.0.0\\hostfxr.dll", NULL, 0); //通过GetProcAddress函数获取到运行时入口函数指针,也就是上面实例化的startupinfo_fptr变量 startupinfo_fptr = (hostfxr_main_startupinfo_fn)GetProcAddress(h, "hostfxr_main_startupinfo"); //通过传入运行时入口函数指针的参数,包括Host_Path,DotNet_Root,ConsoleApp等参数。来运行CLR,用以调用ConsoleApp里面的Main函数入口。 startupinfo_fptr(1, &argvV, Host_Path, DotNet_Root, ConsoleApp); return 0; }然后引入上面步骤二里面保存记事本的文件hostfxr.h。
如下图所示: