using System using System Runtime InteropServices static class RawSeri

 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
using System;
using System.Runtime.InteropServices;
static class RawSerializer <TTarget>
where TTarget : struct
{
public static int Size
{
get
{
return Marshal.SizeOf (typeof (TTarget));
}
}
public static unsafe byte [] Serialize (TTarget target)
{
byte [] raw = new byte [Size];
fixed (byte * rawPointer = raw)
{
IntPtr managedPointer = new IntPtr (rawPointer);
Marshal.StructureToPtr (target, managedPointer, false);
}
return raw;
}
public static unsafe TTarget Deserialize (byte [] raw)
{
object target;
fixed (byte * rawPointer = raw)
{
IntPtr managedPointer = new IntPtr (rawPointer);
target = Marshal.PtrToStructure (managedPointer, typeof (TTarget));
}
return (TTarget) target;
}
}
// 11 bytes in total
[StructLayout (LayoutKind.Sequential, Pack = 1)]
struct Data
{
public int SomeField; // 4 bytes
public int OtherField; // 4 bytes
[MarshalAs (UnmanagedType.ByValArray, SizeConst = 3)]
public byte [] DataChunk; // 3 bytes
}
public static class Example