Skip to content

Instantly share code, notes, and snippets.

@DinoChiesa
Created March 8, 2013 21:48
Show Gist options
  • Save DinoChiesa/5120167 to your computer and use it in GitHub Desktop.
Save DinoChiesa/5120167 to your computer and use it in GitHub Desktop.
Raw Serializer in C#
internal class RawSerializer<T>
{
public T RawDeserialize( byte[] rawData )
{
return RawDeserialize( rawData , 0 );
}
public T RawDeserialize( byte[] rawData , int position )
{
int rawsize = Marshal.SizeOf( typeof(T) );
if( rawsize > rawData.Length )
return default(T);
IntPtr buffer = Marshal.AllocHGlobal( rawsize );
try
{
Marshal.Copy( rawData, position, buffer, rawsize );
return (T) Marshal.PtrToStructure( buffer, typeof(T) );
}
finally
{
Marshal.FreeHGlobal( buffer );
}
}
public byte[] RawSerialize( T item )
{
int rawSize = Marshal.SizeOf( typeof(T) );
byte[] rawData = new byte[ rawSize ];
IntPtr buffer = Marshal.AllocHGlobal( rawSize );
try
{
Marshal.StructureToPtr( item, buffer, false );
Marshal.Copy( buffer, rawData, 0, rawSize );
}
finally
{
Marshal.FreeHGlobal( buffer );
}
return rawData;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment