예제 #1
0
        public static T ToStruct <T>(this byte[] bytes)
        {
            EndiannessHelper.RespectEndianness(typeof(T), bytes);
            GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);

            try
            {
                return((T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T)));
            }
            finally
            {
                handle.Free();
            }
        }
예제 #2
0
        public static byte[] ToBytes <T>(this T data)
        {
            byte[]   bytes  = new byte[Marshal.SizeOf(data)];
            GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);

            try
            {
                IntPtr rawDataPtr = handle.AddrOfPinnedObject();
                Marshal.StructureToPtr(data, rawDataPtr, false);
            }
            finally
            {
                handle.Free();
            }

            EndiannessHelper.RespectEndianness(typeof(T), bytes);

            return(bytes);
        }