123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- using System.Runtime.InteropServices;
- namespace Bmp.Core.Common.Utility
- {
- public static class MarshalExtension
- {
- public static T ReadStruct<T>(this Stream stream)
- {
- var buffer = stream.ReadBytes(Marshal.SizeOf(typeof(T)));
- var handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
- var result = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T))!;
- handle.Free();
- return result;
- }
- public static void ReadStruct<T>(this Stream stream, ref T result)
- {
- var buffer = stream.ReadBytes(Marshal.SizeOf(typeof(T)));
- var handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
- result = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T))!;
- handle.Free();
- }
- public static long NetworkOrderToHostOrder(this long value)
- {
- if (BitConverter.IsLittleEndian)
- {
- var bytes = BitConverter.GetBytes(value);
- Array.Reverse(bytes); // 反转字节数组以转换为本机端序
- return BitConverter.ToInt64(bytes, 0);
- }
- return value; // 本机端序和大端序相同,无需转换
- }
- public static ulong NetworkOrderToHostOrder(this ulong value)
- {
- if (BitConverter.IsLittleEndian)
- {
- var bytes = BitConverter.GetBytes(value);
- Array.Reverse(bytes); // 反转字节数组以转换为本机端序
- return BitConverter.ToUInt64(bytes, 0);
- }
- return value; // 本机端序和大端序相同,无需转换
- }
- public static int NetworkOrderToHostOrder(this int value)
- {
- if (BitConverter.IsLittleEndian)
- {
- var bytes = BitConverter.GetBytes(value);
- Array.Reverse(bytes); // 反转字节数组以转换为本机端序
- return BitConverter.ToInt32(bytes, 0);
- }
- return value; // 本机端序和大端序相同,无需转换
- }
- public static uint NetworkOrderToHostOrder(this uint value)
- {
- if (BitConverter.IsLittleEndian)
- {
- var bytes = BitConverter.GetBytes(value);
- Array.Reverse(bytes); // 反转字节数组以转换为本机端序
- return BitConverter.ToUInt32(bytes, 0);
- }
- return value; // 本机端序和大端序相同,无需转换
- }
- public static short NetworkOrderToHostOrder(this short value)
- {
- if (BitConverter.IsLittleEndian)
- {
- var bytes = BitConverter.GetBytes(value);
- Array.Reverse(bytes); // 反转字节数组以转换为本机端序
- return BitConverter.ToInt16(bytes, 0);
- }
- return value; // 本机端序和大端序相同,无需转换
- }
- public static ushort NetworkOrderToHostOrder(this ushort value)
- {
- if (BitConverter.IsLittleEndian)
- {
- var bytes = BitConverter.GetBytes(value);
- Array.Reverse(bytes); // 反转字节数组以转换为本机端序
- return BitConverter.ToUInt16(bytes, 0);
- }
- return value; // 本机端序和大端序相同,无需转换
- }
- }
- }
|