-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?

Lian
  • 1
  • 1
  • Just like it says, your MSIL is not correct. The stack is imbalanced, consider removing the Ldc_I4 instruction. – Hans Passant Mar 04 '17 at 23:50
  • What do you mean with: the stack is imbalanced? If I remove Ldc_I4 instruction then it would do nothing, that's not what I want. The behavior I want is like declaring a value that could be use or not. Can I do that? – Lian Mar 07 '17 at 03:46

1 Answers1

0

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.

Regis Portalez
  • 4,675
  • 1
  • 29
  • 41