I know how to create a dynamic method by injecting IL for say a * 2;
However I want to be it like a * b where b is consntant.
Consider this.
int b = SomeClassInstance.Multiplier;
Func<int,int> MultA = CreateDynMethod(b);
for(int i = 0; i < 1000; i++)
{
int a = GetValueSomewhere();
int result = MultA(a);
Console.WriteLine(result);
}
See.. b is the same for all 1000 iteration. However I dont know what it is going to be. 0 1 2 or whatever.
My question is how can I embed the b value in IL as a constant.
This is very important distinction – I dont want to calculate var a * var b. I want (if for example b == 2 in run-time) to create IL which does a * 2.
I have reason to do so. If you please answer the question as it written. Thank you.
EDIT. Here is what I could write with your help. Please tell what do you think
static Func<int, int> IL_EmbedConst(int b)
{
var method = new DynamicMethod("EmbedConst", typeof(int), new[] { typeof(int) } );
var il = method.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldc_I4, b);
il.Emit(OpCodes.Mul);
il.Emit(OpCodes.Ret);
return (Func<int, int>)method.CreateDelegate(typeof(Func<int, int>));
}
You want the
ldc.i4opcode.That will load an int onto the stack, which can then be followed by a
mul.You could use it like this:
By the way, you don’t really need to build methods from IL here. This method would work as well: