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

前端 未结 14 1105
难免孤独
难免孤独 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:22

    Have a look at these methods:

    byte [] StructureToByteArray(object obj)
    {
        int len = Marshal.SizeOf(obj);
    
        byte [] arr = new byte[len];
    
        IntPtr ptr = Marshal.AllocHGlobal(len);
    
        Marshal.StructureToPtr(obj, ptr, true);
    
        Marshal.Copy(ptr, arr, 0, len);
    
        Marshal.FreeHGlobal(ptr);
    
        return arr;
    }
    
    void ByteArrayToStructure(byte [] bytearray, ref object obj)
    {
        int len = Marshal.SizeOf(obj);
    
        IntPtr i = Marshal.AllocHGlobal(len);
    
        Marshal.Copy(bytearray,0, i,len);
    
        obj = Marshal.PtrToStructure(i, obj.GetType());
    
        Marshal.FreeHGlobal(i);
    }
    

    This is a shameless copy of another thread which I found upon Googling!

    Update : For more details, check the source

提交回复
热议问题