【问题标题】:How to represent typeof(Int32&) type in DynamicMethod Emit如何在 DynamicMethod Emit 中表示 typeof(Int32&) 类型
【发布时间】:2017-05-16 01:06:01
【问题描述】:

我有以下代码:

    delegate void RefAction(ref Int32 i);// use ref keyword
    static RefAction CreateRefGenerator(){
        // How to represent typeof(Int32&)type in here??
        Type[] types ={ typeof(Int32)};
        var dm = new DynamicMethod("RefAction"+Guid.NewGuid().ToString(), null, types, true);
        var il = dm.GetILGenerator();
        il.Emit(OpCodes.Nop);
        il.Emit(OpCodes.Ldarg_1);
        il.Emit(OpCodes.Ldc_I4_S,10);
        il.Emit(OpCodes.Stind_I4);
        il.Emit(OpCodes.Ret);

        return (RefAction)dm.CreateDelegate(typeof(RefAction));
    }

运行后得到如下错误:

因为它的签名或安全透明度与委托类型的签名或安全透明度不兼容。

以下正常工作:

  static RefAction CreateRefGenerator(){
        Type[] types = { typeof(Int32).MakeByRefType() };
        ...
  }

【问题讨论】:

    标签: c# cil emit dynamicmethod


    【解决方案1】:

    您必须使用Type.MakeByRefType method 来创建您的引用类型。

    当作为 ref 参数传递时,返回一个表示当前类型的 Type 对象


    您的 il 代码中也可能存在错误:Afaik 动态方法始终是静态的,因此第一个显式参数可以在索引零而不是索引处找到。

    【讨论】:

    • 运行时错误:操作可能会破坏运行时稳定性。
    • @Kenny 这个答案是正确的。第一个参数是typeof(int).MakeByRefType(),位于索引零处,因此应该用ldarg.0 加载。这对我行得通。如果您想要多个引用,请在循环中发出代码。
    • 有点遗憾你不能做 typeof(ref T),虽然我认为强制执行适当的堆栈范围是一件苦差事。
    猜你喜欢
    • 2017-08-18
    • 1970-01-01
    • 1970-01-01
    • 2020-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多