DIY Serialization

Forgot about putting this up as promised. Of course, this is a very simplistic example with only one variable sized field. If you had more, you'd have to also serialize those field's sizes and reconstruction becomes a bit more complicated.

But the important part about this, is really the whole concept of pinning some memory down so that you can manipulate it directly and then releasing it back to the control of the Garbage collector. Pretty cool, really.

[StructLayout(LayoutKind.Sequential)]
struct DIYSerialize
{
  public Int32 Id;
  public byte[] Data;

  public DIYSerialize(Int32 id, string data)
  {
    this.Id = id;
    this.Data = Encoding.ASCII.GetBytes(data);
  }
  public DIYSerialize(byte[] Raw)
  {
    Int32 size = Raw.Length;
    IntPtr pnt = Marshal.AllocHGlobal(size);
    GCHandle pin = GCHandle.Alloc(pnt,GCHandleType.Pinned);
    Marshal.Copy(Raw,0,pnt,size);
    this = (DIYSerialize)Marshal.PtrToStructure(pnt,typeof(DIYSerialize));
    pin.Free();
  }
  public byte[] Serialize()
  {
    Int32 size = Marshal.SizeOf(Id.GetType()) + Data.Length;
    IntPtr pnt = Marshal.AllocHGlobal(size);
    GCHandle pin = GCHandle.Alloc(pnt);
    Marshal.StructureToPtr(this,pnt,false);
    byte[] d = new byte[size];
    Marshal.Copy(pnt,d,0,Data.Length);
    pin.Free();
    Marshal.FreeHGlobal(pnt);
    return d;
  }
}