1. 程式人生 > >位元組轉化為結構體BytesToStruct

位元組轉化為結構體BytesToStruct

//結構體轉位元組陣列
    public byte[] StructToBytes (object structObj)
    {
        
        int 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; } finally { Marshal.FreeHGlobal (buffer);//釋放記憶體 } }
//位元組轉結構體 public object BytesToStruct (byte[] bytes, Type strcutType) {
int size = Marshal.SizeOf (strcutType); IntPtr buffer = Marshal.AllocHGlobal (size); try { Marshal.Copy (bytes, 0, buffer, size); return Marshal.PtrToStructure (buffer, strcutType); } finally { Marshal.FreeHGlobal (buffer); } }