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.
49 lines
2.1 KiB
49 lines
2.1 KiB
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<T>(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<T>(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>(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>(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 |
|
} |
|
}
|
|
|