byte[]和结构互转

//struct转byte[]

public  byte[] StructTOBytes(object obj)

        {
            int size = Marshal.SizeOf(obj);
            //创建byte数组
            byte[] bytes = new byte[size];
            IntPtr structPtr = Marshal.AllocHGlobal(size);
            //将结构体拷贝到分配好的内存空间
            Marshal.StructureToPtr(obj, structPtr, false);
            //从内存空间拷贝到byte数组
            Marshal.Copy(structPtr, bytes, 0, size);
            //释放内存空间
            Marshal.FreeHGlobal(structPtr);
            return bytes;

        }


        /// 结构体List转byte数组
        public static byte[] StructToBytes(List<Student> list)
        {
            //得到结构体的大小
            int iItemSize = Marshal.SizeOf(typeof(Student));
            int size = iItemSize * list.Count;
            //创建byte数组
            byte[] bytes = new byte[size];
            //分配结构体大小的内存空间
            IntPtr structPtr = Marshal.AllocHGlobal(iItemSize);
            int iBeginIndex = 0;
            foreach (Student item in list)
            {
                
                //将结构体拷到分配好的内存空间
                Marshal.StructureToPtr(item, structPtr, true);
                //从内存空间拷到byte数组
                Marshal.Copy(structPtr, bytes, iBeginIndex, iItemSize);
                iBeginIndex = iBeginIndex + iItemSize;
            }
            //释放内存空间
            Marshal.FreeHGlobal(structPtr);
            //返回byte数组
            return bytes;
        }

 //byte[]转换为struct
        public  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);
            }
        }

调用:  student m = new student();
               student a = (student)BytesToStruct(buffer, m.GetType());


如果student中有string类型的要申明string占用固定长度

 [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)]
public string StrudentName;



猜你喜欢

转载自blog.csdn.net/xml714467338/article/details/72281593