c# - DynamicMethod 调用因 StackOverFlowException 而终止

标签 c# dynamicmethod ilgenerator

我有这个类(简化示例)

public class Foo
{
    public object Bar(Type type)
    {
        return new object();
    }
}

并且我想使用 DynamicMethodBar 实例上调用 Bar 方法,如图所示下面:

MethodInfo methodInfo = typeof(Foo).GetMethod(nameof(Foo.Bar), new[] { typeof(Type) });
DynamicMethod method = new DynamicMethod("Dynamic Bar", 
                                         typeof(object), 
                                         new []{ typeof(Type) }, 
                                         typeof(Foo).Module);

ILGenerator ilGenerator = method.GetILGenerator();
ilGenerator.Emit(OpCodes.Ldarg_0);
ilGenerator.EmitCall(OpCodes.Call, method, null); // I feel like this is wrong...
ilGenerator.Emit(OpCodes.Ret);

Func<Type, object> func = (Func<Type, object>) method.CreateDelegate(typeof(Func<Type, object>));

// Attempt to call the function:
func(typeof(Foo));

但是,它并没有按预期工作,而是中止了

Process is terminated due to a StackOverFlowException.


有人可以告诉我我做错了什么吗?是不是参数不匹配? 如何在 Bar 的特定实例上调用 Func

最佳答案

ilGenerator.EmitCall(OpCodes.Call, method, null); // I feel like this is wrong...

您目前正在编写方法;您可能打算在这里调用 methodInfo。请注意,这需要是一个 static 方法才能使用 Call - 如果它是一个实例方法,您可能应该使用 CallVirt。由于您没有传入 Foo 的实例,因此不清楚目标实例将来自何处;您需要将两个 值加载到堆栈上以调用实例方法Foo.Bar(Type type) - 而您目前只加载一个。

显示 Delegate.CreateDelegate 用法:

var methodInfo = typeof(Foo).GetMethod(nameof(Foo.Bar), new[] { typeof(Type) });
var foo = new Foo();

// if Foo is known ahead of time:
var f1 = (Func<Type, object>)Delegate.CreateDelegate(
    typeof(Func<Type, object>), foo, methodInfo);

// if Foo is only known per-call:
var f2 = (Func<Foo, Type, object>)Delegate.CreateDelegate(
    typeof(Func<Foo, Type, object>), null, methodInfo);

Console.WriteLine(f1(typeof(string)));

Console.WriteLine(f2(foo, typeof(string)));

关于c# - DynamicMethod 调用因 StackOverFlowException 而终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49531982/

相关文章:

c# - 生产环境中transactionScope和ServiceBus的问题

c# - 如何在DynamicMethod中调用DynamicMethod

c# - 公共(public)语言运行时检测到无效程序 - ILGenerator

cil - 在 VB.Net 中使用 System.Reflection.Emit.ILGenerator 调用 Random?

c# - 如何使用 signalR 通知数据库更改

c# - WinDbg sosex无法调试

c# - 使用 StreamReader 和 XmlSerializer 的内存泄漏

c# - 为什么这个 DynamicMethod (ldarg.1, newobj, ret) 会触发 VerificationException?

c# - DynamicMethod.CreateDelegate 的异常,几乎相同的 MSDN 示例

c# - 使 DynamicMethod 调用其他方法