c#結構體和字節流之間的相互轉換


結構體轉byte數組

1  首先要明白 ,是 在那個命名空間下  System.Runtime.InteropServices;

2  首先得到結構體的大小

2  開辟相應的內存空間

3  將結構體填充進開辟的內存空間

4  從內存空間拷貝進byte數組

5  不要忘記釋放內存哦

  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數組,轉換為結構體

1  開辟內存空間

2  用數組填充內存空間

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);
        }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM