【问题标题】:Re-interpreting a byte array as an array of structs将字节数组重新解释为结构数组
【发布时间】:2010-09-15 10:38:51
【问题描述】:

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

【问题讨论】:

标签: c# struct bytearray unsafe


【解决方案1】:

试试这个。我已经测试过了,它可以工作:

    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

【讨论】:

  • @SargeBorsch 是的。第一个 for 循环是复制到新缓冲区。有问题吗?
猜你喜欢
  • 2016-12-04
  • 1970-01-01
  • 1970-01-01
  • 2015-02-21
  • 2021-11-29
  • 1970-01-01
  • 2021-12-23
  • 1970-01-01
  • 2018-07-25
相关资源
最近更新 更多