/// <summary> /// 字节流转换为结构体 /// </summary> /// <param name="bytes">需要转换的字节流</param> /// <param name="structType">转换结果的结构体类型</param> /// <returns></returns> public Object BytesToStruct(byte[] bytes, Type structType) { int size = Marshal.SizeOf(structType); using (UnManagedMemory mem = new UnManagedMemory(size)) { IntPtr buffer = (IntPtr)mem.Handle; Marshal.Copy(bytes, 0, buffer, size); return(Marshal.PtrToStructure(buffer, structType)); } }
/// <summary> /// 结构体转为字节流 /// </summary> /// <param name="structure">需要转换的结构体对象</param> /// <returns></returns> public byte[] StructToBytes(Object structure) { int size = Marshal.SizeOf(structure); byte[] bytes = new byte[size]; using (UnManagedMemory mem = new UnManagedMemory(size)) { IntPtr buffer = (IntPtr)mem.Handle; Marshal.StructureToPtr(structure, buffer, false); Marshal.Copy(buffer, bytes, 0, size); return(bytes); } }