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

March 16, 2011

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{        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;            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.
tags: ,
one comment