c# 结构体与byte互转

2021-03-09 16:29

阅读:410

标签:copy   etop   data   数组   type   hal   buffer   oar   color   

 ///   
        /// 由结构体转换为byte数组  
        ///   
        public static byte[] StructureToByte(T structure)
        {
            int size = Marshal.SizeOf(typeof(T));
            byte[] buffer = new byte[size];
            IntPtr bufferIntPtr = Marshal.AllocHGlobal(size);
            try
            {
                Marshal.StructureToPtr(structure, bufferIntPtr, true);
                Marshal.Copy(bufferIntPtr, buffer, 0, size);
            }
            finally
            {
                Marshal.FreeHGlobal(bufferIntPtr);
            }
            return buffer;
        }

        ///   
        /// 由byte数组转换为结构体  
        ///   
        public static T ByteToStructure(byte[] dataBuffer)
        {
            object structure = null;
            int size = Marshal.SizeOf(typeof(T));
            IntPtr allocIntPtr = Marshal.AllocHGlobal(size);
            try
            {
                Marshal.Copy(dataBuffer, 0, allocIntPtr, size);
                structure = Marshal.PtrToStructure(allocIntPtr, typeof(T));
            }
            finally
            {
                Marshal.FreeHGlobal(allocIntPtr);
            }
            return (T)structure;
        }
        static byte[] GetByte(T obj)
        {
            MemoryStream ms = new MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(ms, obj);
            byte[] result = ms.ToArray();
            ms.Close();
            ms.Dispose();
            return result;
        }

 

c# 结构体与byte互转

标签:copy   etop   data   数组   type   hal   buffer   oar   color   

原文地址:https://www.cnblogs.com/chlm/p/12732935.html


评论


亲,登录后才可以留言!