How to convert a structure to a byte array in C#?

前端 未结 14 1037
难免孤独
难免孤独 2020-11-22 09:59

How do I convert a structure to a byte array in C#?

I have defined a structure like this:

public struct CIFSPacket
{
    public uint protocolIdentifi         


        
14条回答
  •  自闭症患者
    2020-11-22 10:31

    This is fairly easy, using marshalling.

    Top of file

    using System.Runtime.InteropServices
    

    Function

    byte[] getBytes(CIFSPacket str) {
        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;
    }
    

    And to convert it back:

    CIFSPacket fromBytes(byte[] arr) {
        CIFSPacket str = new CIFSPacket();
    
        int size = Marshal.SizeOf(str);
        IntPtr ptr = Marshal.AllocHGlobal(size);
    
        Marshal.Copy(arr, 0, ptr, size);
    
        str = (CIFSPacket)Marshal.PtrToStructure(ptr, str.GetType());
        Marshal.FreeHGlobal(ptr);
    
        return str;
    }
    

    In your structure, you will need to put this before a string

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 100)]
    public string Buffer;
    

    And make sure SizeConst is as big as your biggest possible string.

    And you should probably read this: http://msdn.microsoft.com/en-us/library/4ca6d5z7.aspx

提交回复
热议问题