我这里有两种方法可以将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;
}
我找到解决办法了。
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;
}