/// <summary>
/// Takes a bytearray and uses it to create a struct of the given type
/// and populate it with the data of the byte array.
/// NOTE: this method only works withs Structs which have a fixed size
/// </summary>
/// <param name="bytearray"> The data that will be used to initialize the struct</param>
/// <param name="type">The type of the expected struct</param>
/// <returns>A new struct instance with its fields initialized with the bytes from bytearray</returns>
public
static
object
ByteArrayToStructure(
byte
[] bytearray, Type type)
{
int
len = Marshal.SizeOf(type);
IntPtr i = Marshal.AllocHGlobal(len);
Marshal.Copy(bytearray, 0, i, len);
var obj = Marshal.PtrToStructure(i,type);
Marshal.FreeHGlobal(i);
return
obj;
}
/// <summary>
/// Returns the contents of an struct as a byte array.
/// It only works with fixed length structs.
/// </summary>
/// <param name="obj">the struct that holds the data that will be returned in the byte array</param>
/// <returns>A byte array with the contents of the struct</returns>
public
static
byte
[] StructToByteArray(
this
object
obj)
{
int
len = Marshal.SizeOf(obj);
byte
[] arr =
new
byte
[len];
IntPtr ptr = Marshal.AllocHGlobal(len);
Marshal.StructureToPtr(obj, ptr,
true
);
Marshal.Copy(ptr, arr, 0, len);
Marshal.FreeHGlobal(ptr);
return
arr;
}