Tuesday, December 4, 2012

How to convert a Structure to byte array

So many times we need to use a structure to hold and organize some data. Then later we will need to send this structure to a client or another system via serial or ethernet. C# is not a very cast friendly! so you can't just cast the structure to a byte array like you can do in C or C++.





I have this strucure for example.
struct str_packet
{
    byte           key;
    byte    []    offset;
    byte          length;
    byte    []    data;
    short         Check_Sum;
};
 
 
 
 
 /*
    This Function will return a Byte Array that contains the data in the structure
*/ 
static byte [] StructureToByteArray(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;
}
/*
This Function will set a pointer to the new data extracted from the Byte Array
*/
static void ByteArrayToStructure(byte [] bytearray, ref object obj)
{
    int len = Marshal.SizeOf(obj);
    IntPtr i = Marshal.AllocHGlobal(len);
    
    Marshal.Copy(bytearray,0, i,len);
    obj = Marshal.PtrToStructure(i, obj.GetType());
    Marshal.FreeHGlobal(i);
}

No comments:

Post a Comment