gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:08:51 24 4
gpt4 key购买 nike

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

最佳答案

试试这个(我在修改后的行上发表了评论):

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");

关于.net - 如何将 .entrypoint 指令添加到方法(动态程序集),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1147130/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com