Class struct and byte [] conversion class, byte Conversion

Source: Internet
Author: User

Class struct and byte [] conversion class, byte Conversion

    public static class StructConvert    {        public static object BytesToStruct(byte[] bytes, Type strcutType)        {            int size = Marshal.SizeOf(strcutType);            IntPtr buffer = Marshal.AllocHGlobal(size);            try            {                Marshal.Copy(bytes, 0, buffer, size);                return Marshal.PtrToStructure(buffer, strcutType);            }            finally            {                Marshal.FreeHGlobal(buffer);            }        }        public static byte[] StructToBytes(object structObj)        {            int size = Marshal.SizeOf(structObj);            IntPtr buffer = Marshal.AllocHGlobal(size);            try            {                Marshal.StructureToPtr(structObj, buffer, false);                byte[] bytes = new byte[size];                Marshal.Copy(buffer, bytes, 0, size);                return bytes;            }            finally            {                Marshal.FreeHGlobal(buffer);            }        }    }

Class struct example. Both struct and class can be converted according to project requirements.

    [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]    public struct MapRecord    {        public int Id;        public int Rebirth;        public int CoorX;        public int CoorY;        public int CoorZ;        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 204)]        public byte[] Unknown1;        public int Dir;        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]        public byte[] Unknown2;        public int MiniMap;        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]        public byte[] Unknown3;    }

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.