Reputation: 1
I'm just trying to generate code that just generate a int constant. Here is the code: string name = Path.GetFileNameWithoutExtension(outputPath); string filename = Path.GetFileName(outputPath);
AssemblyName assemblyName = new AssemblyName(name);
AssemblyBuilder assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave); //, Path.GetDirectoryName(outputPath));
ModuleBuilder moduleBuilder = assembly.DefineDynamicModule(name, filename);
TypeBuilder programType = moduleBuilder.DefineType(name + ".Program");
MethodBuilder mainMethod = programType.DefineMethod("Main", MethodAttributes.Static, typeof(void), System.Type.EmptyTypes);
assembly.SetEntryPoint(mainMethod);
ILGenerator generator = mainMethod.GetILGenerator();
generator.Emit(OpCodes.Ldc_I4, (int)Value);
generator.Emit(OpCodes.Ret);
programType.CreateType();
assembly.Save(filename);
And when i execute the .exe it gives that exception Why?
Upvotes: -1
Views: 648
Reputation: 4860
As specified here, you define a method with a void return type.
But the IL you generates returns a int (the content of your stack before the ret instruction).
If you replace the defineMethod line by
MethodBuilder mainMethod = programType.DefineMethod("Main", MethodAttributes.Static, typeof(int), System.Type.EmptyTypes);
You'll get things right.
You can usually find most of IL errors using ILspy to disassemble your executable (or library).
In your case, you'd see :
static void Main()
{
12;
}
which is obviously wrong.
Upvotes: 0