- // Struct 转换为 byte[]
- public static byte[] StructToBytes(object structure)
- {
- int size = Marshal.SizeOf(structure);
- IntPtr buffer = Marshal.AllocHGlobal(size);
- try
- {
- Marshal.StructureToPtr(structure, buffer, false);
- byte[] bytes = new byte[size];
- Marshal.Copy(buffer, bytes, 0, size);
- return bytes;
- }
- finally
- {
- Marshal.FreeHGlobal(buffer);
- }
- }
- // byte[] 转换为 Struct
- public static 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);
- }
- }
- #endregion
来源: http://www.bubuko.com/infodetail-2900495.html