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

后端 未结 5 1157
刺人心
刺人心 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:51

    You could use pointers if you really want to copy each byte and not have a copy but the same object, similar to this:

    var structPtr = (byte*)&yourStruct;
    var size = sizeof(YourType);
    var memory = new byte[size];
    fixed(byte* memoryPtr = memory)
    {
        for(int i = 0; i < size; i++)
        {
            *(memoryPtr + i) = *structPtr++;
        }
    }
    File.WriteAllBytes(path, memory);
    

    I just tested this and after adding the fixed block and some minor corrections it looks like it is working correctly.

    This is what I used to test it:

    public static void Main(string[] args)
    {
        var a = new s { i = 1, j = 2 };
        var sPtr = (byte*)&a;
        var size = sizeof(s);
        var mem = new byte[size];
        fixed (byte* memPtr = mem)
        {
            for (int i = 0; i < size; i++)
            {
                *(memPtr + i) = *sPtr++;
            }
        }
        File.WriteAllBytes("A:\\file.txt", mem);
    }
    
    struct s
    {
        internal int i;
    
        internal int j;
    }
    

    The result is the following:

    example

    (I manually resolved the hex bytes in the second line, only the first line was produced by the program)

提交回复
热议问题