반응형
        public static byte[] StructToByteArray(object objStruct)
        {
            int nSize = Marshal.SizeOf(objStruct);
            byte[] arr = new byte[nSize];
            IntPtr ptr = Marshal.AllocHGlobal(nSize);
            Marshal.StructureToPtr(objStruct, ptr, false);
            Marshal.Copy(ptr, arr, 0, nSize);
            Marshal.FreeHGlobal(ptr);

            return arr;
        }

        public static T ByteArrayToStruct<T>(byte[] buffer) where T : struct
        {
            int nSize = Marshal.SizeOf(typeof(T));

            if (nSize > buffer.Length)
            {
                throw new Exception();
            }

            IntPtr ptr = Marshal.AllocHGlobal(nSize);
            Marshal.Copy(buffer, 0, ptr, nSize);
            T objStruct = (T)Marshal.PtrToStructure(ptr, typeof(T));
            Marshal.FreeHGlobal(ptr);
            return objStruct;
        }

+ Recent posts