Created
March 8, 2013 21:48
-
-
Save DinoChiesa/5120167 to your computer and use it in GitHub Desktop.
Raw Serializer in C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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