Calling varargs method via DynamicMethod

一曲冷凌霜 提交于 2019-12-21 12:21:46

问题


I'm trying to call unmanaged printf-like function using DynamicMethod. At runtime I get a

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

Is this a limitation of runtime or my emited code is wrong?

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:


While the exception is exceptionally cryptic, I guess it is thrown due to some security checks related to calling varargs method, or it may be a bug in them. What works is to provide a logically associated type or module:

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

Works flawlessly then.



来源:https://stackoverflow.com/questions/29458616/calling-varargs-method-via-dynamicmethod

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