BinaryUitl.cs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Runtime.InteropServices;
  5. using System.Runtime.Serialization.Formatters.Binary;
  6. using System.Text;
  7. namespace Ips.Library.Basic
  8. {
  9. public static class BinaryUitl
  10. {
  11. public static byte[] StructToBytes<T>(T obj) where T : struct
  12. {
  13. int size = Marshal.SizeOf(obj);
  14. IntPtr ptr = Marshal.AllocHGlobal(size);
  15. byte[] buf = new byte[size];
  16. try
  17. {
  18. Marshal.StructureToPtr(obj, ptr, false);
  19. Marshal.Copy(ptr, buf, 0, buf.Length);
  20. }
  21. finally
  22. {
  23. Marshal.FreeHGlobal(ptr);
  24. }
  25. return buf;
  26. }
  27. public static T BytesToStruct<T>(byte[] buf, int startIndex = 0) where T : struct
  28. {
  29. int size = Marshal.SizeOf<T>();
  30. IntPtr ptr = Marshal.AllocHGlobal(size);
  31. T result;
  32. try
  33. {
  34. Marshal.Copy(buf, startIndex, ptr, size);
  35. result = Marshal.PtrToStructure<T>(ptr);
  36. }
  37. finally
  38. {
  39. Marshal.FreeHGlobal(ptr);
  40. }
  41. return result;
  42. }
  43. }
  44. }