結構體轉byte數組數組
1 首先要明白 ,是 在那個命名空間下 System.Runtime.InteropServices;spa
2 首先獲得結構體的大小code
2 開闢相應的內存空間blog
3 將結構體填充進開闢的內存空間內存
4 從內存空間拷貝進byte數組io
5 不要忘記釋放內存哦class
public static byte[] StructToBytes(object structObj, int size = 0) { if (size == 0) { size = Marshal.SizeOf(structObj); //獲得結構體大小 } IntPtr buffer = Marshal.AllocHGlobal(size); //開闢內存空間 try { Marshal.StructureToPtr(structObj, buffer, false); //填充內存空間 byte[] bytes = new byte[size]; Marshal.Copy(buffer, bytes, 0, size); //填充數組 return bytes; } catch (Exception ex) { Debug.LogError("struct to bytes error:" + ex); return null; } finally { Marshal.FreeHGlobal(buffer); //釋放內存 } }
同理,接受到的byte數組,轉換爲結構體object
1 開闢內存空間命名空間
2 用數組填充內存空間bug
3 將內存空間的內容轉換爲結構體
4 一樣不要忘記釋放內存
public static object BytesToStruct(byte[] bytes, Type strcutType, int nSize) { if (bytes == null) { Debug.LogError("null bytes!!!!!!!!!!!!!"); } int size = Marshal.SizeOf(strcutType); IntPtr buffer = Marshal.AllocHGlobal(nSize); //Debug.LogError("Type: " + strcutType.ToString() + "---TypeSize:" + size + "----packetSize:" + nSize); try { Marshal.Copy(bytes, 0, buffer, nSize); return Marshal.PtrToStructure(buffer, strcutType); } catch (Exception ex) { Debug.LogError("Type: " + strcutType.ToString() + "---TypeSize:" + size + "----packetSize:" + nSize); return null; } finally { Marshal.FreeHGlobal(buffer); } }