470,848 Members | 1,587 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,848 developers. It's quick & easy.

Issue emitting an Int16 value in a DynamicMethod...

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(TestHand ler));
Console.WriteLine(handler());
}
Jul 11 '06 #1
2 1050
"Nathan Baulch" <na***********@gmail.comwrote:
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

--
http://barrkel.blogspot.com/
Jul 11 '06 #2
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);
Jul 12 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

1 post views Thread by Arjen | last post: by
10 posts views Thread by Vinay | last post: by
4 posts views Thread by hharry | last post: by
1 post views Thread by Phoenix | last post: by
1 post views Thread by gleave | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.