C# – Copying a structure to byte array as is, and back

March 16, 2011

tags: ,
one comment

A customer asked me today how he can serialize a structure to a byte array for sending to hardware controller. The controller requires that the structure will be sent as is, with no padding or packing. As long as he sure (we dealing with unsafe code) that the data is correct and the size if fine, he can do the following:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Runtime.InteropServices;
 
namespace ConsoleApplication20
{
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    internal struct MyStruct
    {
        public byte c;
        public int a;
        public ushort b;
    }
    class Program
    {
        static unsafe void Main(string[] args)
        {
            var s = new MyStruct { c = 1, a = 7, b = 15 };
 
            int length = Marshal.SizeOf(s);
            // or this
            int size = sizeof(MyStruct);
 
            var b = new byte[size];
            Marshal.Copy(new IntPtr(&s), b, 0, size);
            //And back…
            var r = new MyStruct();
            Marshal.Copy(b, 0, new IntPtr(&r), size);
        }
    }
}
 
 

Don’t forget to compile with /unsafe flag.

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*

one comment

  1. Alex MichelJuly 14, 2011 ב 20:20

    Hi,
    I found following implementation to perform better:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Runtime.InteropServices;

    namespace PlayWithSerializers
    {
    class Program
    {

    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    internal struct MyStruct
    {
    public byte c;
    public int a;
    public ushort b;
    }

    unsafe static byte[] Serialize(MyStruct item)
    {
    byte[] message = new byte[sizeof(MyStruct)];
    fixed (byte* ptr = &message[0])
    {
    *((MyStruct*)(ptr)) = item;
    }
    return message;
    }

    unsafe static MyStruct Deserialize(byte[] message)
    {
    int size = sizeof(MyStruct);
    MyStruct result = new MyStruct();
    fixed (byte* ptr = &message[0])
    {
    result = *((MyStruct*)(ptr));
    }
    return result;
    }

    static void Main(string[] args)
    {
    MyStruct a = new MyStruct() { a = 1, b = 2, c = 3 };
    byte[] message = Serialize(a);
    MyStruct b = Deserialize(message);
    }
    }
    }

    Regards

    Reply