将字节数组重新解释为结构数组

时间:2010-09-15 10:38:52

标签: c# struct bytearray unsafe

我有一个字节数组,我想重新解释为一个blittable结构数组,理想情况下没有复制。使用不安全的代码很好。我知道字节数,以及我想在最后得到的结构数。

public struct MyStruct
{
    public uint val1;
    public uint val2;
    // yadda yadda yadda....
}


byte[] structBytes = reader.ReadBytes(byteNum);
MyStruct[] structs;

fixed (byte* bytes = structBytes)
{
    structs = // .. what goes here?

    // the following doesn't work, presumably because
    // it doesnt know how many MyStructs there are...:
    // structs = (MyStruct[])bytes;
}

1 个答案:

答案 0 :(得分:4)

试试这个。我已经测试过并且有效:

    struct MyStruct
    {
        public int i1;
        public int i2;
    }

    private static unsafe MyStruct[] GetMyStruct(Byte[] buffer)
    {
        int count = buffer.Length / sizeof(MyStruct);
        MyStruct[] result = new MyStruct[count];
        MyStruct* ptr;

        fixed (byte* localBytes = new byte[buffer.Length])
        {
            for (int i = 0; i < buffer.Length; i++)
            {
                localBytes[i] = buffer[i];
            }
            for (int i = 0; i < count; i++)
            {
                ptr = (MyStruct*) (localBytes + sizeof (MyStruct)*i);
                result[i] = new MyStruct();
                result[i] = *ptr;
            }
        }


        return result;
    }

用法:

        byte[] bb = new byte[] { 0,0,0,1 ,1,0,0,0 };
        MyStruct[] structs = GetMyStruct(bb); // i1=1 and i2=16777216