Public Static Class Structcopyer
{
// Serialization and deserialization, but external files are not needed
// 1. Convert struct to byte []
Public Static Byte [] structtobytes (object structure)
{
Int32 size = marshal. sizeof (structure );
Intptr buffer = marshal. allochglobal (size );
Try
{
Marshal. structuretoptr (structure, buffer,False);
Byte [] bytes =NewByte [size];
Marshal. Copy (buffer, bytes,0, Size );
ReturnBytes;
}
Finally
{
Marshal. freehglobal (buffer );
}
}
//2. byte [] to struct
Public StaticObject bytestostruct (byte [] bytes, type strcuttype)
{
Int32 size = marshal. sizeof (strcuttype );
Intptr buffer = marshal. allochglobal (size );
Try
{
Marshal. Copy (bytes,0, Buffer, size );
ReturnMarshal. ptrtostructure (buffer, strcuttype );
}
Finally
{
Marshal. freehglobal (buffer );
}
}
}
Usage:
// Interfacestruct is a struct
Interfacestruct pinterface = New Interfacestruct ();
Pinterface = (interfacestruct) bytestostruct (bytpipeinfo, pinterface. GetType ());
From: http://www.cnblogs.com/jingmoxukong/articles/2118105.html