gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:27:02 26 4
gpt4 key购买 nike

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

最佳答案

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

    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

关于c# - 将字节数组重新解释为结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3716805/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com