L
Lars Wilhelmsen
Hi Ben,
Feel free to use this method:
public static object RawDeserialize( byte[] rawData, int position, Type
anyType )
{
int rawsize = Marshal.SizeOf( anyType );
if( rawsize > rawData.Length )
return null;
IntPtr buffer = Marshal.AllocHGlobal( rawsize );
Marshal.Copy( rawData, position, buffer, rawsize );
object retobj = Marshal.PtrToStructure( buffer, anyType );
Marshal.FreeHGlobal( buffer );
return retobj;
}
the position is the position into the byte array to start deserializing
from, and the
type is the type of the structure - typof(MESSAGE_LOG_HEADER_STRUCT2).
Remember to cast the return value to the same type too.
And if you want to do vice versa, use this one:
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 );
return rawDatas;
}
Ben Terry said:Can anyone tell me how to get data from a byte array into the following
structure?
Feel free to use this method:
public static object RawDeserialize( byte[] rawData, int position, Type
anyType )
{
int rawsize = Marshal.SizeOf( anyType );
if( rawsize > rawData.Length )
return null;
IntPtr buffer = Marshal.AllocHGlobal( rawsize );
Marshal.Copy( rawData, position, buffer, rawsize );
object retobj = Marshal.PtrToStructure( buffer, anyType );
Marshal.FreeHGlobal( buffer );
return retobj;
}
the position is the position into the byte array to start deserializing
from, and the
type is the type of the structure - typof(MESSAGE_LOG_HEADER_STRUCT2).
Remember to cast the return value to the same type too.
And if you want to do vice versa, use this one:
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 );
return rawDatas;
}