MarshalExtension.cs 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. using System.Runtime.InteropServices;
  2. namespace Bmp.Core.Common.Utility
  3. {
  4. public static class MarshalExtension
  5. {
  6. public static T ReadStruct<T>(this Stream stream)
  7. {
  8. var buffer = stream.ReadBytes(Marshal.SizeOf(typeof(T)));
  9. var handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
  10. var result = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T))!;
  11. handle.Free();
  12. return result;
  13. }
  14. public static void ReadStruct<T>(this Stream stream, ref T result)
  15. {
  16. var buffer = stream.ReadBytes(Marshal.SizeOf(typeof(T)));
  17. var handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
  18. result = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T))!;
  19. handle.Free();
  20. }
  21. public static long NetworkOrderToHostOrder(this long value)
  22. {
  23. if (BitConverter.IsLittleEndian)
  24. {
  25. var bytes = BitConverter.GetBytes(value);
  26. Array.Reverse(bytes); // 反转字节数组以转换为本机端序
  27. return BitConverter.ToInt64(bytes, 0);
  28. }
  29. return value; // 本机端序和大端序相同,无需转换
  30. }
  31. public static ulong NetworkOrderToHostOrder(this ulong value)
  32. {
  33. if (BitConverter.IsLittleEndian)
  34. {
  35. var bytes = BitConverter.GetBytes(value);
  36. Array.Reverse(bytes); // 反转字节数组以转换为本机端序
  37. return BitConverter.ToUInt64(bytes, 0);
  38. }
  39. return value; // 本机端序和大端序相同,无需转换
  40. }
  41. public static int NetworkOrderToHostOrder(this int value)
  42. {
  43. if (BitConverter.IsLittleEndian)
  44. {
  45. var bytes = BitConverter.GetBytes(value);
  46. Array.Reverse(bytes); // 反转字节数组以转换为本机端序
  47. return BitConverter.ToInt32(bytes, 0);
  48. }
  49. return value; // 本机端序和大端序相同,无需转换
  50. }
  51. public static uint NetworkOrderToHostOrder(this uint value)
  52. {
  53. if (BitConverter.IsLittleEndian)
  54. {
  55. var bytes = BitConverter.GetBytes(value);
  56. Array.Reverse(bytes); // 反转字节数组以转换为本机端序
  57. return BitConverter.ToUInt32(bytes, 0);
  58. }
  59. return value; // 本机端序和大端序相同,无需转换
  60. }
  61. public static short NetworkOrderToHostOrder(this short value)
  62. {
  63. if (BitConverter.IsLittleEndian)
  64. {
  65. var bytes = BitConverter.GetBytes(value);
  66. Array.Reverse(bytes); // 反转字节数组以转换为本机端序
  67. return BitConverter.ToInt16(bytes, 0);
  68. }
  69. return value; // 本机端序和大端序相同,无需转换
  70. }
  71. public static ushort NetworkOrderToHostOrder(this ushort value)
  72. {
  73. if (BitConverter.IsLittleEndian)
  74. {
  75. var bytes = BitConverter.GetBytes(value);
  76. Array.Reverse(bytes); // 反转字节数组以转换为本机端序
  77. return BitConverter.ToUInt16(bytes, 0);
  78. }
  79. return value; // 本机端序和大端序相同,无需转换
  80. }
  81. }
  82. }