c# - 通过 DynamicMethod 调用可变参数方法

标签 c# .net-4.0 cil reflection.emit dynamicmethod

我正在尝试使用 DynamicMethod 调用类似 printf 的非托管函数。在运行时我得到一个

BadImageFormatException:Index not found. (Exception from HRESULT: 0x80131124)

这是运行时的限制还是我发出的代码有误?

public class Program
{
    [DllImport("msvcrt40.dll",CallingConvention = CallingConvention.Cdecl)]
    public static extern int printf(string format, __arglist);

    static void Main(string[] args) {

        var method = new DynamicMethod("printf", typeof(void), new Type[0], true);
        var il = method.GetILGenerator();

        il.Emit(OpCodes.Ldstr, " %s=%d\n");
        il.Emit(OpCodes.Ldstr, "a");
        il.Emit(OpCodes.Ldc_I4_0);
        il.EmitCall(OpCodes.Call, typeof(Program).GetMethod("printf", BindingFlags.Public | BindingFlags.Static), new Type[] { typeof(string), typeof(int) });
        il.Emit(OpCodes.Pop);
        il.Emit(OpCodes.Ret);

        var action = (Action)method.CreateDelegate(typeof(Action));
        action.Invoke();
    }
}

最佳答案

虽然这个异常异常神秘,但我猜它是由于一些与调用 varargs 方法相关的安全检查而抛出的,或者它可能是其中的一个错误。有效的是提供逻辑关联的类型或模块:

var method = new DynamicMethod("printf", typeof(void), new Type[0], typeof(Program), true);

然后完美地工作。

关于c# - 通过 DynamicMethod 调用可变参数方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29458616/

相关文章:

C# Path.GetTempPath 返回 "Could not find a part of the path"错误

c# - 什么时候使用 Partitioner 类?

generics - Mono.Cecil:从其他程序集中调用 GENERIC 基类的方法

c# - .NET:为什么嵌套类具有在外部类中声明的泛型?

c# - 强制关闭文件

c# - 将属性作为参数的通用函数

c# - 如何在javascript中存储值并在服务器端使用它

c# - .NET REGEX 匹配匹配空字符串

c# - BigInteger阶乘的并行计算

c# - CLR 如何优化属性引用?