Is it possible to call a DynamicMethod from MethodBuilder/ConstructorBuilder

拈花ヽ惹草 提交于 2021-02-09 08:55:22

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/11059165/is-it-possible-to-call-a-dynamicmethod-from-methodbuilder-constructorbuilder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!