4

我有一个字节数组,我想将它重新解释为一个 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;
}
4

1 回答 1

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
于 2010-09-15T12:29:59.937 回答