通过DynamicMethod调用varargs方法

时间:2015-04-05 15:00:54

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

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

  

BadImageFormatException:找不到索引。 (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();
    }
}

1 个答案:

答案 0 :(得分:4)

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

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

然后完美无瑕地工作。