C#代码的编译与执行过程(摘自ms inside c#)
2024-07-21 02:20:19
供稿:网友
1.you write source code in c#.
2.you then compile it using the c# compiler (csc.exe) into an exe.
3.the c# compiler outputs the msil code and a manifest into a read-only part of the exe that has a standard pe (win32-portable executable) header.
so far, so good. however, here's the important part: when the compiler creates the output, it also imports a function named _ corexemain from the .net runtime.
4.when the application is executed, the operating system loads the pe, as well as any dependent dynamic-link libraries (dlls), such as the one that exports the _ corexemain function (mscoree.dll), just as it does with any valid pe.
5.the operating system loader then jumps to the entry point inside the pe, which is put there by the c# compiler. once again, this is exactly how any other pe is executed in windows.
however, since the operating system obviously can't execute the msil code, the entry point is just a small stub that jumps to the _ corexemain function in mscoree.dll.
6.the _ corexemain function starts the execution of the msil code that was placed in the pe.
7.since msil code cannot be executed directly—because it's not in a machine-executable format—the clr compiles the msil by using a just-in-time (jit) compiler (or jitter) into native cpu instructions as it processes the msil. jit compiling occurs only as methods in the program are called. the compiled executable code is cached on the machine and is recompiled only if there's some change to the source code.