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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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;
}
}
// Example structure of 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
{
public static void Main ()
{
Data data = new Data
{
SomeField = 123,
OtherField = 321,
DataChunk = new byte [] { 0, 1, 2 }
};
byte [] serialized = RawSerializer <Data>.Serialize (data);
Data deserialized = RawSerializer <Data>.Deserialize (serialized);
Console.WriteLine ("Serialized struct size: {0}\n", serialized.Length);
Console.WriteLine (deserialized.SomeField);
Console.WriteLine (deserialized.OtherField);
Console.WriteLine (deserialized.DataChunk.Length);
}
}