Search code examples
c#reflectioncilreflection.emitdynamicmethod

How to call DynamicMethod in DynamicMethod


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

Solution

  • 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.