c# - 为什么在 C# 应用程序中将 IL 代码打包到 exe 中?

标签 c# .net clr

我试图通过在 C# 可执行文件上执行 ILDASM 和 ILASM 往返来重新生成 exe。据我了解,ILDASM 生成的 .il 文件足以生成 .exe。

我很好奇为什么.NET framework 被设计为使用exe 文件进行部署,而不是将.il 文件部署给用户。 c# 编译器不能生成 .il 文件,而 JIT 编译器直接使用 .il 文件作为输入吗?仅仅是因为操作系统需要 .exe 扩展名来调用加载程序,还是因为文件大小或性能方面的考虑?

PS:这个问题没有实际意义。我问这个问题是为了让我的概念更清楚,因为我确信我还欠缺很多。

最佳答案

仅仅为了迎合 .NET 而添加另一种类型的扩展没有任何意义。

.NET 可执行文件是 PE 文件,它们提供最少量的 native 代码来引导正确版本的 CLR 并将 IL 拉入内存并移交给 CLR。​​

Windows 本身就知道如何处理 PE 文件和 EXE 中内置的间接机制,Windows 也不需要了解 .NET。

对于 .il 文件,您需要向 Windows 注册扩展,然后确保加载了正确版本的 CLR - 据我所知,您只能将扩展关联到一个可执行文件。

要支持多个版本的 CLR,您需要某种中介,然后检查您的 .il 文件以确定要加载哪个 CLR……之后事情变得复杂和脆弱那个。

将所有这些打包到一个 PE 中可以巧妙而优雅地解决这些问题。

虽然这是一篇较旧的文章,但其原则在当前的 .NET Frameworks 中保持不变:

An In-Depth Look into the Win32 Portable Executable File Format, Part 2

关键部分“The .NET Header”解释了它是如何工作的:

Executables produced for the Microsoft .NET environment are first and foremost PE files. However, in most cases normal code and data in a .NET file are minimal. The primary purpose of a .NET executable is to get the .NET-specific information such as metadata and intermediate language (IL) into memory. In addition, a .NET executable links against MSCOREE.DLL. This DLL is the starting point for a .NET process. When a .NET executable loads, its entry point is usually a tiny stub of code. That stub just jumps to an exported function in MSCOREE.DLL (_CorExeMain or _CorDllMain). From there, MSCOREE takes charge, and starts using the metadata and IL from the executable file. This setup is similar to the way apps in Visual Basic (prior to .NET) used MSVBVM60.DLL. The starting point for .NET information is the IMAGE_COR20_HEADER structure, currently defined in CorHDR.H from the .NET Framework SDK and more recent versions of WINNT.H. The IMAGE_COR20_HEADER is pointed to by the IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR entry in the DataDirectory. Figure 10 shows the fields of an IMAGE_COR20_HEADER. The format of the metadata, method IL, and other things pointed to by the IMAGE_COR20_HEADER will be described in a subsequent article.

关于c# - 为什么在 C# 应用程序中将 IL 代码打包到 exe 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5489740/

相关文章:

c# 远程 powershell 创建 AD/Exchange 用户帐户并修改

c# - 如何从文件中删除单个属性(例如只读)?

c# - 实现自定义 JsonWriter (JSON.net)

c# - 非虚实例方法继承是如何解决的?

c# - 使用泛型转换代码

c# - FileStream.Seek 与缓冲读取

c# - 如何删除/替换当前使用的字体

.net - 保持 sql 数据库模式在开发人员之间同步

.net - 您推荐什么有关 .NET CLR 和 CIL 的好书?

c# - 我如何获得对所有托管线程的引用