Reputation: 1950
How do I emit IL to call a DynamicMethod while creating a DynamicMethod?
When calling ILGenerator.Emit(OpCodes.Callvirt, myDynamicMethod);
the IL that is produces results in a MissingMethodException
when executed.
I reproduced the issue with this minimal code:
var dm1 = new DynamicMethod("Dm1", typeof(void), new Type[0]);
dm1.GetILGenerator().Emit(OpCodes.Ret);
var dm2 = new DynamicMethod("Dm2", typeof(void), new Type[0]);
var ilGenerator = dm2.GetILGenerator();
ilGenerator.Emit(OpCodes.Callvirt, dm1);
ilGenerator.Emit(OpCodes.Ret);
dm2.Invoke(null, new Type[0]); // exception raised here
Upvotes: 2
Views: 454
Reputation: 2233
You can indeed call a DynamicMethod
from another DynamicMethod
.
var ilGenerator = dm2.GetILGenerator();
ilGenerator.Emit(OpCodes.Call, dm1);
OpCodes.Callvirt should be used when calling a virtual method on an object (e.g. ToString()
). This does not apply to DynamicMethod
.
OpCodes.Call should instead be used.
Upvotes: 2