Как добавить директиву .entrypoint к методу (динамическая сборка) - PullRequest
4 голосов
/ 18 июля 2009

Я хочу создать простое приложение, используя классы в 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 ]

6 голосов
/ 18 июля 2009

Попробуйте это (я добавил комментарии к измененным строкам):

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 голос
/ 18 июля 2009

Посмотрите на его пример , я только что сам попробовал код, и он работает очень хорошо.

...