using System.Runtime.InteropServices;
using System.Runtime.Serialization.Formatters.Binary;
public static T RawDeserialize<T>(byte[] rawData, int position)
int rawsize = Marshal.SizeOf(typeof(T));
if (rawsize > rawData.Length - position)
throw new ArgumentException("Not enough data to fill struct. Array length from position: "+(rawData.Length-position) + ", Struct length: "+rawsize);
IntPtr buffer = Marshal.AllocHGlobal(rawsize);
Marshal.Copy(rawData, position, buffer, rawsize);
T retobj = (T)Marshal.PtrToStructure(buffer, typeof(T));
Marshal.FreeHGlobal(buffer);
public static byte[] RawSerialize(object anything)
int rawSize = Marshal.SizeOf(anything);
IntPtr buffer = Marshal.AllocHGlobal(rawSize);
Marshal.StructureToPtr(anything, buffer, false);
byte[] rawDatas = new byte[rawSize];
Marshal.Copy(buffer, rawDatas, 0, rawSize);
Marshal.FreeHGlobal(buffer);
public static byte[] Serialize(Data[] t)
BinaryFormatter bF = new BinaryFormatter();
using (MemoryStream mS = new MemoryStream())
result = new byte[mS.Length];
mS.Read(result, 0, result.Length);
public static Data[] Deserialize(byte[] buffer)
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream mS = new MemoryStream())
mS.Write(buffer, 0, buffer.Length);
result = (Data[])bf.Deserialize(mS);
[StructLayout(LayoutKind.Sequential, Pack = 1)]
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public static void Main()
new MyStruct(){ b = 4, s = 8 },
new MyStruct(){ b = 16, s = 32 }
var bytes = Serialize(new Data[] { d });
Console.WriteLine("Total size should be: " + (Marshal.SizeOf(d) + (Marshal.SizeOf(d.arr[0]) * 2)));
Console.WriteLine("Total size: " + bytes.Length);