如何将.entrypoint指令添加到方法(动态程序集)

时间:2009-07-18 09:50:26

标签: .net cil reflection.emit

我想使用System.Reflection.Emit中的类创建一个简单的应用程序。如何将enrypoint指令添加到Main方法?

AssemblyName aName = new AssemblyName("Hello");
AssemblyBuilder aBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(aName, AssemblyBuilderAccess.Save);

ModuleBuilder mBuilder = aBuilder.DefineDynamicModule("Module");

TypeBuilder tb = mBuilder.DefineType("Program", TypeAttributes.Public);

MethodBuilder methodBuilder = tb.DefineMethod("Main", MethodAttributes.Public | MethodAttributes.Static);

ILGenerator ilGenerator = methodBuilder.GetILGenerator();
ilGenerator.EmitWriteLine("Hello!");

aBuilder.SetEntryPoint(methodBuilder);
tb.CreateType();
aBuilder.Save("Hello.exe");

AssemblyBuilder.SetEntryPoint似乎没有达到此目的。

2 个答案:

答案 0 :(得分:6)

试试这个(我已对修改后的行添加评论):

AssemblyName aName = new AssemblyName("Hello");
AssemblyBuilder aBuilder = AppDomain
    .CurrentDomain
    .DefineDynamicAssembly(aName, AssemblyBuilderAccess.Save);
// When you define a dynamic module and want to save the assembly 
// to the disc you need to specify a filename
ModuleBuilder mBuilder = aBuilder
    .DefineDynamicModule("Module", "Hello.exe", false);
TypeBuilder tb = mBuilder
    .DefineType("Program", TypeAttributes.Public);
MethodBuilder methodBuilder = tb
    .DefineMethod("Main", MethodAttributes.Public | MethodAttributes.Static);

ILGenerator ilGenerator = methodBuilder.GetILGenerator();
ilGenerator.EmitWriteLine("Hello!");

// You need to always emit the return operation from a method 
// otherwise you will get an invalid IL
ilGenerator.Emit(OpCodes.Ret);

aBuilder.SetEntryPoint(methodBuilder);
tb.CreateType();
aBuilder.Save("Hello.exe");

答案 1 :(得分:1)

看看他的example,我刚刚尝试了代码并且它非常有用。