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

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

    Variant of the code of Vicent with one less memory allocation:

    public static byte[] GetBytes(T str)
    {
        int size = Marshal.SizeOf(str);
    
        byte[] arr = new byte[size];
    
        GCHandle h = default(GCHandle);
    
        try
        {
            h = GCHandle.Alloc(arr, GCHandleType.Pinned);
    
            Marshal.StructureToPtr(str, h.AddrOfPinnedObject(), false);
        }
        finally
        {
            if (h.IsAllocated)
            {
                h.Free();
            }
        }
    
        return arr;
    }
    
    public static T FromBytes(byte[] arr) where T : struct
    {
        T str = default(T);
    
        GCHandle h = default(GCHandle);
    
        try
        {
            h = GCHandle.Alloc(arr, GCHandleType.Pinned);
    
            str = Marshal.PtrToStructure(h.AddrOfPinnedObject());
    
        }
        finally
        {
            if (h.IsAllocated)
            {
                h.Free();
            }
        }
    
        return str;
    }
    

    I use GCHandle to "pin" the memory and then I use directly its address with h.AddrOfPinnedObject().

提交回复
热议问题