Tuesday, 1 November 2011


Struct to byte array example:


    class Program
    {
        internal struct Header
        {
            public int Size;
            public byte Checksum;
        }

        internal struct Packet
        {
            public Header Header;

            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
            public byte[] Data;
        }
   
        static void Main(string[] args)
        {
            // --------------------------
            // Init
            // --------------------------
            Packet packet = new Packet
            {
                Header = new Header
                {
                    Size = 8,
                    Checksum = 9
                },
                Data = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 }
            };

            // --------------------------
            // Convert to bytes
            // --------------------------
            // Convert to "8 0 0 0 9 0 0 0 0 1 2 3 4 5 6 7"
            byte[] buffer = RawSerialize(packet);

            // --------------------------
            // Convert to object
            // --------------------------
            Packet newPacket = (Packet)RawDeserialize(buffer, 0, typeof(Packet));
        }

        public static object RawDeserialize(byte[] rawData, int position, Type anyType)
        {
            int rawsize = Marshal.SizeOf(anyType);
            if (rawsize > rawData.Length)
                return null;

            IntPtr buffer = Marshal.AllocHGlobal(rawsize);
            Marshal.Copy(rawData, position, buffer, rawsize);
            object retobj = Marshal.PtrToStructure(buffer, anyType);
            Marshal.FreeHGlobal(buffer);
            return retobj;
        }

        public static byte[] RawSerialize(object anything)
        {
            int rawSize = Marshal.SizeOf(anything);
            IntPtr buffer = Marshal.AllocHGlobal(rawSize);
            Marshal.StructureToPtr(anything, buffer, false);
            byte[] rawDatas = new byte[rawSize];
            Marshal.Copy(buffer, rawDatas, 0, rawSize);
            Marshal.FreeHGlobal(buffer);
            return rawDatas;
        }
    }

No comments:

Post a Comment