.net 如何将.entrypoint指令添加到方法(动态程序集)
我想使用System.Reflection.Emit中的类创建一个简单的应用程序。如何将enrypoint指令添加到Main方法.net 如何将.entrypoint指令添加到方法(动态程序集),.net,cil,reflection.emit,.net,Cil,Reflection.emit,我想使用System.Reflection.Emit中的类创建一个简单的应用程序。如何将enrypoint指令添加到Main方法 AssemblyName aName = new AssemblyName("Hello"); AssemblyBuilder aBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(aName, AssemblyBuilderAccess.Save); ModuleBuilder mBuilder = aB
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似乎无法实现这一点。尝试一下(我在修改的行上添加了注释):
看看这个,我自己刚试过这个代码,效果非常好,nicley。谢谢,这很有效。您知道模块需要知道程序集保存到的文件名的原因吗?
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");