How to mutate a boxed value type (primitive or struct) in C#/IL

前端 未结 2 1510
情书的邮戳
情书的邮戳 2021-01-15 09:11

Related to How to mutate a boxed struct using IL I am trying to change the value of a boxed value type but in a generic way, so trying to implement the following method:

2条回答
  •  时光说笑
    2021-01-15 09:58

    One solution, is by making an Unbox method in IL that calls unbox and returns a ref to the type contained in the object:

    .method public hidebysig static !!T&  Unbox(object o) cil managed aggressiveinlining
    {
      .maxstack  1
      ldarg.0
      unbox !!T
      ret
    }
    

    And then using this like:

    public static void MutateValueType(object o, T v)
    {
        ref T ub = ref Unsafe.Unbox(o);
        ub = v;
    }
    

    This correctly outputs:

            var oi = (object)17;
            MutateValueType(oi, 43);
            Console.WriteLine(oi); // 43
    
            var od = (object)17.7d;
            MutateValueType(od, 42.3);
            Console.WriteLine(od); // 42.3
    

    NOTE: This requires C# 7 support for ref returns.

    This might be added to say https://github.com/DotNetCross/Memory.Unsafe but it must also be possible with il.Emit also, so I am looking for that.

提交回复
热议问题