C# Structure to Byte array conversion

By | December 2, 2018

An utility and some code examples how to automatically convert a struct to byte array and back. This comes very handy when implementing protocols.

Add annotations to your structures, for example:

using System.Runtime.InteropServices;

   [StructLayout(LayoutKind.Explicit)]
    public struct Header
    {
        [FieldOffset(0)]
        public MessageType messageType;
        [FieldOffset(1)]
        public CommandStatus commandStatus;
        [FieldOffset(2)]
        public byte receiverAddress;
        [FieldOffset(3)]
        public byte senderAddress;
    }


Convert from struct to byte array and vice versa:

byte[] messageBytes = ByteArray.StructureToByteArray(msg);
ReceivedHeader = ByteArray.ByteArrayToStructure<Header>(receivedPacket);

The ByteArray utility is part of Yats.Utilities NuGet package. Source code:

public static T ByteArrayToStructure<T>(byte[] bytes) where T : struct
{
    GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
    try
    {
        T stuff = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
        return stuff;
    }
    finally
    {
        handle.Free();
    }
}

public static 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;
}

Leave a Reply

Your email address will not be published.