user667967
user667967

Reputation: 648

How to emit code that calls a dynamic method?

I'm trying to emit code that calls a dynamic method that I emitted earlier:

iLGenerator.Emit(OpCodes.Call, dynamicMethod.GetMethodInfo());

It troughs an exception saying: "MethodInfo must be a runtime MethodInfo object"

Is there a way to convert a dynamic method into a runtime method?

Upvotes: 3

Views: 882

Answers (1)

Mike Zboray
Mike Zboray

Reputation: 40818

From what I can tell you've already compiled the DynamicMethod into a delegate using CreateDelegate. However, if you just use the DynamicMethod object directly as the parameter to Emit it should work. A demonstration:

using System.Reflection;
using System.Reflection.Emit;

public class Program
{
    public static void Main(string[] args)
    {
        var dynMethod = new DynamicMethod("test1", typeof(void), Type.EmptyTypes);
        var gen = dynMethod.GetILGenerator();
        gen.EmitWriteLine("Test");
        gen.Emit(OpCodes.Ret);

        var dynMethod2 = new DynamicMethod("test2", typeof(void), Type.EmptyTypes);
        gen = dynMethod2.GetILGenerator();
        gen.Emit(OpCodes.Call, dynMethod);
        gen.Emit(OpCodes.Ret);
        var method2 = (Action)dynMethod2.CreateDelegate(typeof(Action));
        method2();
    }
}

Upvotes: 5

Related Questions