-
Notifications
You must be signed in to change notification settings - Fork 8
/
ByteArray.cs
50 lines (47 loc) · 1.5 KB
/
ByteArray.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using System.Runtime.InteropServices;
namespace DeviceProgramming
{
public static class ByteArray
{
/// <summary>
/// Converts a byte array to a fixed size managed struct.
/// </summary>
/// <typeparam name="T">Type of the resulting struct</typeparam>
/// <param name="bytes">The struct data in raw bytes</param>
/// <returns>The struct created by the byte array input</returns>
public static T ToStruct<T>(this byte[] bytes) where T : struct
{
T s;
GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
try
{
s = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
}
finally
{
handle.Free();
}
return s;
}
/// <summary>
/// Converts a fixed size struct to a byte array.
/// </summary>
/// <param name="obj">The structure to convert</param>
/// <returns>The struct data in raw bytes</returns>
public static byte[] ToBytes(this object obj)
{
int size = Marshal.SizeOf(obj);
byte[] arr = new byte[size];
GCHandle handle = GCHandle.Alloc(obj, GCHandleType.Pinned);
try
{
Marshal.Copy(handle.AddrOfPinnedObject(), arr, 0, size);
}
finally
{
handle.Free();
}
return arr;
}
}
}