-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinaryWriterExtension.cs
89 lines (73 loc) · 2.39 KB
/
BinaryWriterExtension.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
namespace USBTrace_BTSnoop
{
#region Usings
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
#endregion
#region BinaryWriterExtension
public static class BinaryWriterExtension
{
public static void WriteStruct<T>(this BinaryWriter bw, T data, List<int> sizes) where T : struct
{
Type resType = data.GetType();
byte[] buff = new byte[Marshal.SizeOf(resType)];
IntPtr ptr = Marshal.AllocHGlobal(buff.Length);
Marshal.StructureToPtr((object)data, ptr, true);
Marshal.Copy(ptr, buff, 0x0, buff.Length);
Marshal.FreeHGlobal(ptr);
byte[] writebuffer;
if (sizes != null)
{
writebuffer = new byte[buff.Length];
int pos = 0;
foreach (var item in sizes)
{
for (int i = 0; i < item; i++)
{
writebuffer[pos + i] = buff[pos + item - 1 - i];
}
pos += item;
}
}
else
{
writebuffer = buff;
}
bw.Write(writebuffer, 0, buff.Length);
}
public static T ReadStruct<T>(this BinaryReader br, List<int> sizes) where T : struct
{
T result = default(T);
var resType = result.GetType();
int count = Marshal.SizeOf(resType);
byte[] readBuffer;
var readBufferOrg = br.ReadBytes(count);
if (sizes != null)
{
readBuffer = new byte[count];
int pos = 0;
foreach (var item in sizes)
{
for (int i = 0; i < item; i++)
{
readBuffer[pos + i] = readBufferOrg[pos + item - 1 - i];
}
pos += item;
}
}
else
{
readBuffer = readBufferOrg;
}
GCHandle handle = GCHandle.Alloc(readBuffer, GCHandleType.Pinned);
result = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), resType);
handle.Free();
return result;
}
}
#endregion
}