I have code like this to emit IL code that loads integer or string values. But I don't know how to add the decimal
type to that. It isn't supported in the Emit
method. Any solutions to this?
ILGenerator ilGen = methodBuilder.GetILGenerator();
if (type == typeof(int))
{
ilGen.Emit(OpCodes.Ldc_I4, Convert.ToInt32(value, CultureInfo.InvariantCulture));
}
else if (type == typeof(double))
{
ilGen.Emit(OpCodes.Ldc_R8, Convert.ToDouble(value, CultureInfo.InvariantCulture));
}
else if (type == typeof(string))
{
ilGen.Emit(OpCodes.Ldstr, Convert.ToString(value, CultureInfo.InvariantCulture));
}
Not working:
else if (type == typeof(decimal))
{
ilGen.Emit(OpCodes.Ld_???, Convert.ToDecimal(value, CultureInfo.InvariantCulture));
}
Edit: Okay, so here's what I did:
else if (type == typeof(decimal))
{
decimal d = Convert.ToDecimal(value, CultureInfo.InvariantCulture);
// Source: https://msdn.microsoft.com/en-us/library/bb1c1a6x.aspx
var bits = decimal.GetBits(d);
bool sign = (bits[3] & 0x80000000) != 0;
byte scale = (byte)((bits[3] >> 16) & 0x7f);
ilGen.Emit(OpCodes.Ldc_I4, bits[0]);
ilGen.Emit(OpCodes.Ldc_I4, bits[1]);
ilGen.Emit(OpCodes.Ldc_I4, bits[2]);
ilGen.Emit(sign ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);
ilGen.Emit(OpCodes.Ldc_I4, scale);
var ctor = typeof(decimal).GetConstructor(new[] { typeof(int), typeof(int), typeof(int), typeof(bool), typeof(byte) });
ilGen.Emit(OpCodes.Newobj, ctor);
}
But it doesn't generate a newobj
opcode, but instead nop
and stloc.0
. The constructor is found and passed to the Emit
call. What's wrong here? Obviously an InvalidProgramException
is thrown when trying to execute the generated code because the stack is completely messed up.
ilGen.Emit(OpCodes.Ldc_I4, scale)
. You're saying you're loading an I4 (int
), but then use thebyte
overload ofEmit()
. One way to fix that would beilGen.Emit(OpCodes.Ldc_I4, (int)scale);
. – Mcdaniels