.net - 发出IL以调用Math函数

标签 .net cil il

C#调用

Math.Pow(2,3);

在ILDASM中:
ldc.r8   2.
ldc.r8   3.
call     float64[mscorlib]System.Math::Pow(float64, float64)

有人可以告诉我如何通过ILGenerator发出该调用语句吗?谢谢。

最佳答案

这是构建动态方法的示例,该方法将调用静态Math.Pow(double, double)方法:

using System;
using System.Linq;
using System.Reflection.Emit;

class Program
{
    static void Main()
    {
        // define the signature of the dynamic method
        var powIt = new DynamicMethod(
            "PowIt",
            typeof(double),
            new Type[] { typeof(double), typeof(double) },
            typeof(Program).Module
        );

        // get a MethodInfo pointer to the Math.Pow(double, double) static
        // method that we are willing to use in our dynamic method
        var pow = typeof(Math).GetMethod("Pow", new[] { typeof(double), typeof(double) });

        var il = powIt.GetILGenerator();
        // Push the first argument onto the evaluation stack
        il.Emit(OpCodes.Ldarg_0);
        // Push the second argument onto the evaluation stack
        il.Emit(OpCodes.Ldarg_1);
        // Invoke the Math.Pow static method that we obtained a MethodInfo earlier
        // by passing the two arguments that are on the evaluation stack
        il.Emit(OpCodes.Call, pow);

        // Return from the method pushing a return value from the callee's evaluation stack onto the caller's evaluation stack
        il.Emit(OpCodes.Ret);

        // build a delegate from the dynamic method
        var func = (Func<double, double, double>)powIt.CreateDelegate(typeof(Func<double, double, double>));

        // Now invoke the delegate
        Console.WriteLine(func(2, 3));
    }
}

关于.net - 发出IL以调用Math函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8459188/

相关文章:

c# - 使用 'typeof'和 'is'时,c#如何共享引用类型的泛型实现?

c# - 差一错误和突变测试

c# - 在 WPF ComboBox 中设置默认值

c# - 创建二级 AppDomain 挂起

asp.net - .NET 发送带有响应正文的 HTTP 400

c# - 在编译 C# 应用程序时设置平台有什么不同吗?

C# 数据绑定(bind)不更新 WPF

asp.net - 将 MSIL 自动转换为 JavaScript 有用吗?

c# - 为什么我收到异常 : Common Language Runtime detected an invalid program

.net - 为什么生成的 IL 代码以 Nop 开头?