如何将结构数组转换为二进制数组C#语言

问题描述 投票:0回答:1

我这里有两种方法可以将struct解析为字节[],以及将字节[]解析为struct。

那么如何将 "struct数组 "解析为字节数组,以及将字节数组解析为struct数组呢?

byte[] getBytes<T>(T[] str) where T : struct
T[] fromBytes<T>(byte[] byte) where T : struct

/---这里是struct转byte[]---byte[]转struct----。

byte[] getBytes<T>(T str) where T : struct
    {
        int size = Marshal.SizeOf(str);
        byte[] arr = new byte[size];

        IntPtr ptr = Marshal.AllocHGlobal(size);
        Marshal.StructureToPtr(str, ptr, true);
        Marshal.Copy(ptr, arr, 0, size);
        Marshal.FreeHGlobal(ptr);
        return arr;
    }

    T fromBytes<T>(byte[] arr) where T : struct
    {
        T str = new T();

        int size = Marshal.SizeOf(str);
        IntPtr ptr = Marshal.AllocHGlobal(size);

        Marshal.Copy(arr, 0, ptr, size);

        str = (T)Marshal.PtrToStructure(ptr, str.GetType());
        Marshal.FreeHGlobal(ptr);

        return str;
    }
c# .net data-structures marshalling
1个回答
0
投票

我找到解决办法了。

T[] GetStructs<T>(byte[] arr) where T : struct
{
    int size = Marshal.SizeOf(default(T));
    int len = arr.Length / size;
    T[] result = new T[len];

    IntPtr ptr = Marshal.AllocHGlobal(size);
    for (int i = 0; i < len; ++i)
    {
        Marshal.Copy(arr, i * size, ptr, size);
        result[i] = (T)Marshal.PtrToStructure(ptr, typeof(T));
    }
    Marshal.FreeHGlobal(ptr);

    return result;
}

byte[] GetBytes<T>(T[] structAry) where T : struct
{
    int len = structAry.Length;
    int size = Marshal.SizeOf(default(T));
    byte[] arr = new byte[size * len];
    IntPtr ptr = Marshal.AllocHGlobal(size);
    for (int i = 0; i < len; ++i)
    {
        Marshal.StructureToPtr(structAry[i], ptr, true);
        Marshal.Copy(ptr, arr, i * size, size);
    }
    Marshal.FreeHGlobal(ptr);

    return arr;
}
© www.soinside.com 2019 - 2024. All rights reserved.