2

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

11 Comments

Now getting Invalid Program exception.
From what I picked up from other errors, DynamicMethods can only be statics, right? I am copying my IL from an existing method and replacing method calls with dynamics which means instead of calling string.GetHashCode() (for example) it's calling a dyamic GetHashCode(string). From my basic understanding of IL, the 2 should be equivalent (i.e. just a matter of replacing the call instruction and the rest should just work).
@Sellorio I'm running the code in visual studio 2017 and not getting an error. try changing your ctor to new DynamicMethod("Dm1", typeof(void), new Type[0], typeof(object), true);
Yeah the basic code works but my main code isn't functional yet. (see previous comment)
Correct, they are only statics. The only way to add instance methods at runtime is with System.Reflection.Emit.TypeBuilder and not on existing types. You can get your DynamicMethod to mimic an instance method by having the first parameter be of that type. However, there's no way to call it virtually
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.