wei*_*ure 4 .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");
Run Code Online (Sandbox Code Playgroud)
AssemblyBuilder.SetEntryPoint似乎没有实现这一点.
试试这个(我已经对修改过的行进行了评论):
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");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
501 次 |
| 最近记录: |