C# - Cast a byte array to an array of struct and vice-versa (reverse)

后端 未结 5 1111
刺人心
刺人心 2021-01-19 17:05

I would like to save a Color[] to a file. To do so, I found that saving a byte array to a file using \"System.IO.File.WriteAllBytes\" should be very efficient.

I wou

5条回答
  •  迷失自我
    2021-01-19 17:57

    Since .NET Core 2.1, yes we can! Enter MemoryMarshal.

    We will treat our Color[] as a ReadOnlySpan. We reinterpret that as a ReadOnlySpan. Finally, since WriteAllBytes has no span-based overload, we use a FileStream to write the span to disk.

    var byteSpan = MemoryMarshal.AsBytes(colorArray.AsSpan());
    fileStream.Write(byteSpan);
    

    As an interesting side note, you can also experiment with the [StructLayout(LayoutKind.Explicit)] as an attribute on your fields. It allows you to specify overlapping fields, effectively allowing the concept of a union.

    Here is a blog post on MSDN that illustrates this. It shows the following code:

    [StructLayout(LayoutKind.Explicit)]
    public struct MyUnion
    {
        [FieldOffset(0)]
        public UInt16 myInt;
    
        [FieldOffset(0)]
        public Byte byte1;
    
        [FieldOffset(1)]
        public Byte byte2;
    }
    

    In this example, the UInt16 field overlaps with the two Byte fields.

    This seems to be strongly related to what you are trying to do. It gets you very close, except for the part of writing all the bytes (especially of multiple Color objects) efficiently. :)

提交回复
热议问题