using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace LoadStruct { public static class S2B { #region Загрузка/выгрузка данных в структуру public static T BuffToStruct(byte[] arr) { GCHandle gch = GCHandle.Alloc(arr, GCHandleType.Pinned); IntPtr ptr = Marshal.UnsafeAddrOfPinnedArrayElement(arr, 0); T ret = (T)Marshal.PtrToStructure(ptr, typeof(T)); gch.Free(); return default(T); } public static T BuffToClass(byte[] arr) { GCHandle gch = GCHandle.Alloc(arr, GCHandleType.Pinned); IntPtr ptr = Marshal.UnsafeAddrOfPinnedArrayElement(arr, 0); T ret = (T)Marshal.PtrToStructure(ptr, typeof(T)); gch.Free(); return default(T); } public static byte[] StructToBuff(T value) where T : struct { byte[] arr = new byte[Marshal.SizeOf(value)]; // создать массив GCHandle gch = GCHandle.Alloc(arr, GCHandleType.Pinned); // зафиксировать в памяти IntPtr ptr = Marshal.UnsafeAddrOfPinnedArrayElement(arr, 0); // и взять его адрес Marshal.StructureToPtr(value, ptr, true); // копировать в массив gch.Free(); // снять фиксацию return arr; } public static byte[] ClassToBuff(T value) where T : class { byte[] arr = new byte[Marshal.SizeOf(value)]; // создать массив GCHandle gch = GCHandle.Alloc(arr, GCHandleType.Pinned); // зафиксировать в памяти IntPtr ptr = Marshal.UnsafeAddrOfPinnedArrayElement(arr, 0); // и взять его адрес Marshal.StructureToPtr(value, ptr, true); // копировать в массив gch.Free(); // снять фиксацию return arr; } #endregion } }