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
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 ofTypeBuilder.DefineMethodand theMethodBuilderinstance it returns.DynamicMethodobjects are handled entirely differently by the .NET runtime than whatReflection.Emituses. Once you’ve defined your method using theMethodBuilder, you can use it as your second parameter toILGenerator.Emit.