VisualStudio/C#

[C#] Struct를 byte로 변환, byte를 Struct로 변환

usingsystem 2023. 2. 2. 10:51
728x90
   static byte[] StructToByte(object obj)
        {
            //구조체 사이즈 
            int size = Marshal.SizeOf(obj);

            //사이즈 만큼 메모리 할당 받기
            byte[] buffer = new byte[size];
            IntPtr ptr = Marshal.AllocHGlobal(size);

            //구조체 주소값 가져오기
            Marshal.StructureToPtr(obj, ptr, false);

            //메모리 복사 
            Marshal.Copy(ptr, buffer, 0, size);
            Marshal.FreeHGlobal(ptr);

            return buffer;
        }
        public static byte[] StructToByte<T>(T structure) where T : struct
        {
            byte[] buffer = new byte[Marshal.SizeOf(typeof(T))];
            GCHandle gcHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
            Marshal.StructureToPtr(structure, gcHandle.AddrOfPinnedObject(), false);
            gcHandle.Free();
            return buffer;
        }
        public static object ByteToStruct(byte[] buffer, Type type)
        {
            try
            {
                // Buffer의 Pointer Handle값을 가져온다.
                GCHandle gcHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
                // Handle값의 포인터를    ` Structure로 복사한다.
                object obj = Marshal.PtrToStructure(gcHandle.AddrOfPinnedObject(), type);
                // 사용한 Buffer의 Pointer를 Clear 한다.
                gcHandle.Free();
                // Structure를 반환한다.
                return obj;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        public static T ByteToStruct<T>(byte[] buffer) where T : struct
        {
            int size = Marshal.SizeOf(typeof(T));
            if (size > buffer.Length)
            {
                throw new Exception();
            }

            IntPtr ptr = Marshal.AllocHGlobal(size);
            Marshal.Copy(buffer, 0, ptr, size);
            T obj = (T)Marshal.PtrToStructure(ptr, typeof(T));
            Marshal.FreeHGlobal(ptr);
            return obj;
        }
728x90