Emitting delegate function call

♀尐吖头ヾ 提交于 2020-02-20 07:39:21

问题


I have the following C# code:

public static double f2(Func<double, double> f, double x)
{
    return f(x);
}   

And here it's IL code:

.method public hidebysig static 
    float64 f2 (
        class [mscorlib]System.Func`2<float64, float64> f,
        float64 x
    ) cil managed 
{
    // Method begins at RVA 0x20bd
    // Code size 8 (0x8)
    .maxstack 8

    IL_0000: ldarg.0
    IL_0001: ldarg.1
    IL_0002: callvirt instance !1 class [mscorlib]System.Func`2<float64, float64>::Invoke(!0)
    IL_0007: ret
}

How can I to emit

callvirt instance !1 class [mscorlib]System.Func`2<float64, float64>::Invoke(!0)

insturction through the System.Reflection.Emit or better through the Mono.Cecil?

What !1 and !0 are stands for?


回答1:


The !n syntax is a reference to a generic argument.

In this example ...

!0 is a reference to the first generic argument of Func<double, double> (used as the type of the argument of the Invoke method)

!1 is a reference to the second generic generic argument of Func<double, double> (used as the return type of Invoke)

EDIT: Your method using System.Reflection.Emit ...

var dynamicMethod = new DynamicMethod(
    "f2Dynamic", 
    typeof(double), 
    new Type[] { typeof(Func<double, double>), typeof(double) });

var il = dynamicMethod.GetILGenerator();

il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Callvirt, typeof(Func<double, double>).GetMethod("Invoke"));
il.Emit(OpCodes.Ret);

var f2Dynamic = 
    (Func<Func<double, double>, double, double>)dynamicMethod.CreateDelegate(
        typeof(Func<Func<double, double>, double, double>));

Console.WriteLine(f2(x => x * x, 10.0));        // prints 100
Console.WriteLine(f2Dynamic(x => x * x, 10.0)); // prints 100

EDIT2: corrected the !n explanation after a hint of @kvb



来源:https://stackoverflow.com/questions/12808673/emitting-delegate-function-call

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