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

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

最佳答案

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

    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/

相关文章:

c# - 在 C# 中以管理员权限启动程序

c# - 卡住多个工作表中的 Pane C#

c# - 什么是空!声明是什么意思?

c++ - 将函数指针赋值给函数指针

将17位数据组合成字节数组

c# 从字节数组创建 xml

c# - 自定义 'ExportFactory'

c - 请帮助我理解 C 中不熟悉的结构语法

struct - 如何从标准 SQL 中的数组结构返回结构数组?

java - 在 Java 中不使用 new 运算符将字节数组转换为字符串