通过DynamicMethod的可变参数调用方法 [英] Calling varargs method via DynamicMethod

查看:142
本文介绍了通过DynamicMethod的可变参数调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图调用使用DynamicMethod的非托管类printf函数。在运行时,我收到了

  

BadImageFormatException:指数没有找到。 (从HRESULT异常:   0x80131124)

这是运行时的限制或我emited code是错的?

 公共类节目
{
    [的DllImport(MSVCRT40.DLL,CallingConvention = CallingConvention.Cdecl)
    公共静态外部INT的printf(字符串格式,__arglist);

    静态无效的主要(字串[] args){

        VAR方法=新的DynamicMethod的(printf上的typeof(无效),新类型[0],真正的);
        变种IL = method.GetILGenerator();

        il.Emit(欧普codes.Ldstr,%s =%d个\ N);
        il.Emit(欧普codes.Ldstr,A);
        il.Emit(欧普codes.Ldc_I4_0);
        il.EmitCall(欧普codes.Call的typeof(程序).GetMethod(printf上,BindingFlags.Public | BindingFlags.Static),新类型[] {typeof运算(字符串)的typeof(INT)});
        il.Emit(欧普codes.Pop);
        il.Emit(欧普codes.Ret);

        VAR行动=(行动)method.CreateDelegate(typeof运算(动作));
        action.Invoke();
    }
}
 

解决方案

而唯独是非常神秘的,我估计是由于与调用可变参数的方法某些安全检查抛出,或者它可能是一个错误在其中。什么工作是提供一种逻辑关联类型或模块

  VAR方法=新的DynamicMethod的(printf上的typeof(无效),新类型[0]的typeof(程序),真正的);
 

完美的作品呢。

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();
    }
}

解决方案

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.

这篇关于通过DynamicMethod的可变参数调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆