4

我想使用 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 似乎没有实现这一点。

4

2 回答 2

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");
于 2009-07-18T10:11:35.807 回答
1

看看他的例子,我自己也试过代码,效果很好。

于 2009-07-18T10:19:16.820 回答