How to Compile with ngen.exe and How to run the native code that is generated?

假如想象 提交于 2019-11-29 02:49:08

问题


I want to compile a C# program using ngen command line for a special purpose. So I create a console application in VS2010 and named it ngentest. A file by name ngentest.vshost.exe is created in vs2010\projects\ngentest\bin\debug. I used this file as a ngen command argument in VS2010 command prompt, as follows:

ngen "c:\documents\vs2010\projects\ngentest\bin\debug\ngentest.vshost.exe"

But when I do this, I can't receive PublicKeyToken and I couldn't find any assembly anywhere! If my assembly is created, where it is? And how I can find it? How I can run it(with command, or...!) to get my output?

Otherwise when I build my project with build ngen from Build menu from VS, some file were created in mentioned directory, and one of them is ngentest.exe.


回答1:


When you compile your C# code, it gets compiled into an IL assembly. And NGEN takes IL assembly as an input and installs the assembly and its dependencies into Native Image Cache.

For your example binary, you need to open an admin VS Command prompt, then type the following

ngen install ngentest.exe

This would install your exe and its dependency dll files into the Native Image Cache. You use the filename to the assembly here.

Then when you run your exe, the .NET runtime will load and run the native image installed to the Native Image Cache. You don't need to take any extra step to have .NET run the Native Image. The runtime checks the Native Image Cache to see if there is a valid Native Image for the IL assembly.

You can verify that a native image is installed by typing the following command:

ngen display ngentest

In this case you must use the assembly name. Note that 32 bit ngen will only install and display 32 bit, assemblies and 64 bit ngen only 64 bitassemblies.

See http://blogs.msdn.com/b/junfeng/archive/2007/02/18/native-image-loading.aspx for more info on Native Image loading.

Note that ngentest.vhost.exe is an artifact created by VS to provide better debugging experience. It is used by VS. You shouldn't be using that for NGEN or anything for that matter. See the question: What is the purpose of the vshost.exe file? for more info.



来源:https://stackoverflow.com/questions/20144213/how-to-compile-with-ngen-exe-and-how-to-run-the-native-code-that-is-generated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!