终端一体化运控平台
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

51 regels
1.4 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Runtime.InteropServices;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace BPASmartClient.GSIceCream
  8. {
  9. public class IcPack
  10. {
  11. private const int BASIC_LENGTH = 5;
  12. public static byte[] StructureToByte<T>(T structure)
  13. {
  14. int size = Marshal.SizeOf(typeof(T));
  15. byte[] buffer = new byte[size];
  16. IntPtr bufferIntPtr = Marshal.AllocHGlobal(size);
  17. try
  18. {
  19. Marshal.StructureToPtr(structure, bufferIntPtr, true);
  20. Marshal.Copy(bufferIntPtr, buffer, 0, size);
  21. }
  22. finally
  23. {
  24. Marshal.FreeHGlobal(bufferIntPtr);
  25. }
  26. return buffer;
  27. }
  28. /// <summary>
  29. /// 由byte数组转换为结构体
  30. /// </summary>
  31. public static T ByteToStructure<T>(byte[] dataBuffer)
  32. {
  33. object structure = null;
  34. int size = Marshal.SizeOf(typeof(T));
  35. IntPtr allocIntPtr = Marshal.AllocHGlobal(size);
  36. try
  37. {
  38. Marshal.Copy(dataBuffer, 0, allocIntPtr, size);
  39. structure = Marshal.PtrToStructure(allocIntPtr, typeof(T));
  40. }
  41. finally
  42. {
  43. Marshal.FreeHGlobal(allocIntPtr);
  44. }
  45. return (T)structure;
  46. }
  47. }
  48. }