Issue emitting an Int16 value in a DynamicMethod...

N

Nathan Baulch

For some reason I keep getting an InvalidProgramException when trying to emit a short (Int16) value in a DynamicMethod.

The following code should replicate my problem.


private delegate object TestHandler();

private static void Main()
{
DynamicMethod method = new DynamicMethod("temp", typeof(object), null, typeof(Program));
ILGenerator il = method.GetILGenerator();
il.Emit(OpCodes.Ldc_I4, (short)1000);
il.Emit(OpCodes.Box, typeof(short));
il.Emit(OpCodes.Ret);
TestHandler handler = (TestHandler)method.CreateDelegate(typeof(TestHandler));
Console.WriteLine(handler());
}
 
B

Barry Kelly

Nathan Baulch said:
For some reason I keep getting an InvalidProgramException when
trying to emit a short (Int16) value in a DynamicMethod.
il.Emit(OpCodes.Ldc_I4, (short)1000);

Ldc_I4 takes a 4-byte integer as its argument, but you are handing it a
2-byte integer. That's why you get an invalid program exception.

The runtime stack on the CLI doesn't know about shorts. Check out
partition I, 12.3.2.1 in the CLI spec (Ecma 335 3rd ed) for more
information about the types the runtime stack actually supports.

Check out III, 3.40 for the ldc instruction. You'll see there that you
should use:

il.Emit(OpCodes.Ldc_I4, 1000);
il.Emit(OpCodes.Conv_I2);

-- Barry
 
N

Nathan Baulch

Check out III, 3.40 for the ldc instruction. You'll see there that you
should use:

il.Emit(OpCodes.Ldc_I4, 1000);
il.Emit(OpCodes.Conv_I2);

Excellent, that worked just nicely!
For the benefit of the newsgroup, I also had a similar issue with ulong
(UInt64) values which I solved in a similar way:

il.Emit(OpCodes.Ldc_I8, (long)val);
il.Emit(OpCodes.Conv_U8);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top