views:

44

answers:

1

I've got a byte array that I want to re-interpret as an array of blittable structs, ideally without copying. Using unsafe code is fine. I know the number of bytes, and the number of structs that I want to get out at the end.

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  A: 

Try this. I have tested and it works:

    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;
    }

Usage:

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