.Net Framework下面如何生成AOT呢?

概括

1.介绍

现在的现代化的.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生成本地机器码,然后执行。

2.用法

应该怎么用它呢?
一:代码
假如说你有以下.Net Frameworker代码,项目名称NgenDemo

static void Main(string[] args)
{
    Console.WriteLine("hello Ngen Call The Main Method");
    Console.ReadLine();
}

二.注意事项:
注意一:把VS里的AnyCpu切换成X64
注意二:打开VS命令行工具,选择64位的
注意三:要以管理员的身份运行64位VS命令行工具
三:生成
比如把以上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路径

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

里面看到一堆文件,它就是生成本机映像,以及本机缓存。此后在本机运行的时候,可以直接双击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路径下的文件支持,才能够运行。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

野生的狒狒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值