• .Net FrameWork下如何生成AOT呢?
  • 发布于 2个月前
  • 237 热度
    0 评论
前言
有人问.Net FrameWorker可以AOT吗?其实AOT预编译,在.Net FrameWorker1.0里面就有了。它叫做Ngen,只不过当时称呼生成本机映像,实际上还是一个东西,也就是预编译。很多小伙伴还在用.Net FrameWorker版本,本篇也来看下。

概括
一.介绍
现在的.Net已经到了.Net8了,它的AOT程序已经可以单个Exe运行在MacOS/Linux/Win等平台上。但是在.Net FrameWorker上面如果想用AOT应该怎么搞呢?微软很早之前就提供了一个小工具,叫做:Ngen.exe。它跟你安装Visual Studio的时候一起安装进来了。它的路径一般的在:
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\ngen.exe //注意这里是64位的
它就是让不跨平台的.Net Frameworker生成本地机器码,然后执行。
二.用法
应该怎么用它呢?
1:代码
假如说你有以下.Net Frameworker代码,项目名称NgenDemo
static void Main(string[] args)
{
    Console.WriteLine("hello Ngen Call The Main Method");
    Console.ReadLine();
}
2.注意事项:
注意一:把VS里的AnyCpu切换成X64
注意二:打开VS命令行工具,选择64位的
注意三:要以管理员的身份运行64位VS命令行工具
3:生成
比如把以上NgenDemo这个项目放到桌面上。在Visual Studio里面摁F5运行下,在目录:
C:\Users\Administrator\Desktop\NgenDemo\bin\x64\Debug
下面会生成:NgenDemo.exe。

打开VS命令行工具:
x64 Native Tools Command Prompt for VS 2022  //注意这里是64位的
运行如下命令:ngen.exe install后面跟着NgenDemo.exe路径
// 堆代码 duidaima.com
C:\Windows\System32>ngen.exe install "C:\Users\Administrator\Desktop\NgenDemo\bin\x64\Debug\NgenDemo.exe"
Microsoft (R) CLR Native Image Generator - Version 4.8.9065.0
Copyright (c) Microsoft Corporation.  All rights reserved.
1>    Compiling assembly C:\Users\Administrator\Desktop\NgenDemo\bin\x64\Debug\NgenDemo.exe (CLR v4.0.30319) ...
查看下生成的映像是否正确:
C:\Windows\System32>ngen.exe display "C:\Users\Administrator\Desktop\NgenDemo\bin\x64\Debug\NgenDemo.exe"
Microsoft (R) CLR Native Image Generator - Version 4.8.9065.0
Copyright (c) Microsoft Corporation.  All rights reserved.
NGEN Roots:
C:\Users\Administrator\Desktop\NgenDemo\bin\x64\Debug\NgenDemo.exe
NGEN Roots that depend on "C:\Users\Administrator\Desktop\NgenDemo\bin\x64\Debug\NgenDemo.exe":
C:\Users\Administrator\Desktop\NgenDemo\bin\x64\Debug\NgenDemo.exe
Native Images:
NgenDemo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null <debug>
可以看到映像已经生成了。
到目录:
C:\Windows\assembly\NativeImages_v4.0.30319_64 //注意它这个最后面的64是64位
里面看到一堆文件,它就是生成本机映像,以及本机缓存。此后在本机运行的时候,可以直接双击NgenDemo.exe就可以运行了。如果想要卸载本机映像,运行如下命令:
C:\Windows\System32>ngen.exe uninstall "C:\Users\Administrator\Desktop\NgenDemo\bin\x64\Debug\NgenDemo.exe"
Microsoft (R) CLR Native Image Generator - Version 4.8.9065.0
Copyright (c) Microsoft Corporation.  All rights reserved.
Uninstalling assembly C:\Users\Administrator\Desktop\NgenDemo\bin\x64\Debug\NgenDemo.exe
就可以卸载了。以上就是.Net Framework生成的本机映像。它有一些缺陷,每个机器上都要生成一次,其次它的程序集缓存不能合并到一起,需要C:\Windows\assembly路径下的文件支持,才能够运行。

所以后面微软开启了corert项目以及现在的nativeAOT项目,都是意图取代它。
用户评论