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

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

    This example here is only applicable to pure blittable types, e.g., types that can be memcpy'd directly in C.

    Example - well known 64-bit struct

    [StructLayout(LayoutKind.Sequential)]  
    public struct Voxel
    {
        public ushort m_id;
        public byte m_red, m_green, m_blue, m_alpha, m_matid, m_custom;
    }
    

    Defined exactly like this, the struct will be automatically packed as 64-bit.

    Now we can create volume of voxels:

    Voxel[,,] voxels = new Voxel[16,16,16];
    

    And save them all to a byte array:

    int size = voxels.Length * 8; // Well known size: 64 bits
    byte[] saved = new byte[size];
    GCHandle h = GCHandle.Alloc(voxels, GCHandleType.Pinned);
    Marshal.Copy(h.AddrOfPinnedObject(), saved, 0, size);
    h.Free();
    // now feel free to save 'saved' to a File / memory stream.
    

    However, since the OP wants to know how to convert the struct itself, our Voxel struct can have following method ToBytes:

    byte[] bytes = new byte[8]; // Well known size: 64 bits
    GCHandle h = GCHandle.Alloc(this, GCHandleType.Pinned);
    Marshal.Copy(hh.AddrOfPinnedObject(), bytes, 0, 8);
    h.Free();
    

提交回复
热议问题