Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to call a DynamicMethod from MethodBuilder/ConstructorBuilder

I have an ILGenerator created from ConstructorBuilder, and I want to create and call a DynamicMethod with it but I get an InvalidOperationException - Unable to import a global method or field from a different module.

var constructorBuilder = typeBuilder.DefineConstructor(...);
var ilGenFromCtor = constructorBuilder.GetILGenerator();
.
.
.
var dynamicMethod = new DynamicMethod("Name", ReturnType, Type.EmptyTypes, true);
var ilGenFromDynamicMethod = dynamicMethod.GetILGenerator();
.
.
var @delegate = dynamicMethod.CreateDelegate();

ilGenFromCtor.Emit(OpCodes.Call, @delegate.Method);

--Or

ilGenFromCtor.Emit(OpCodes.Call, dynamicMethod);

10x
like image 781
Sagi Avatar asked Dec 12 '25 20:12

Sagi


1 Answers

Because you're actually defining an entire, complete assembly at runtime, you're going to have to declare the method somewhere within the assembly (perhaps within the class from which you got the ConstructorBuilder) by using one of the overloads of TypeBuilder.DefineMethod and the MethodBuilder instance it returns. DynamicMethod objects are handled entirely differently by the .NET runtime than what Reflection.Emit uses. Once you've defined your method using the MethodBuilder, you can use it as your second parameter to ILGenerator.Emit.

like image 117
Adam Maras Avatar answered Dec 14 '25 08:12

Adam Maras



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!