How to mutate a boxed struct using IL

后端 未结 5 1065
执笔经年
执笔经年 2020-12-24 07:41

Imagine we have a mutable struct (yes, don\'t start):

public struct MutableStruct
{
    public int Foo { get; set; }
    public override string          


        
5条回答
  •  一个人的身影
    2020-12-24 08:37

    Here you go:

    Just use unsafe :)

    static void Main(string[] args)
    {
      object foo = new MutableStruct {Foo = 123};
      Console.WriteLine(foo);
      Bar(foo);
      Console.WriteLine(foo);
    }
    
    static unsafe void Bar(object foo)
    {
      GCHandle h = GCHandle.Alloc(foo, GCHandleType.Pinned);
    
      MutableStruct* fp = (MutableStruct*)(void*)  h.AddrOfPinnedObject();
    
      fp->Foo = 789;
    }
    

    IL implementation is left as an exercise to the reader.

    Update:

    Based on the Kevin's answer, here is a minimal working example:

    ldarg.0
    unbox      MutableStruct
    ldarg.1
    call       instance void MutableStruct::set_Foo(int32)
    ret
    

提交回复
热议问题