For an USB and serial application, I implement a protocol, and in C/C++ it can be neatly done by structure casting into the buffer, which it makes it handy to encode / decode from data to a byte array, which can then be forwarded to an USB or Serial port.
The other end is communicating with a micro controller. An advantage of this, is that the structure and packing / unpacking mechanism can be a shared code between the host application and the micro-controller application.
Here is an example of a data packing into a char buffer.
Edit: Note that the structure is packed, which means there is no padding between the types.
#pragma pack(push,2)
typedef struct
{
uint32_t address ;
uint32_t len;
uint16_t crc;
} FlashData;
#pragma pack(pop)
unsigned char buf[size + sizeof(FlashData)] __attribute__((aligned));
FlashData *flashData = (FlashData*) &buf[0];
flashData->address = startAddr;
flashData->len = size;
[...]
Is there a simple way to reproduce this sort of casting in C#?
Many years ago I did similar communication in C# but I remember I had to serialize data an manually unpack, which was a pain.
There are some C# example of copying C# data structure to byte arrays, but since every object and type are inherited in C#, I am not sure that would be a good solution.
Another way could be to have a solution with both C++ and C# project, C++ taking care of low level communication and C# higher level and UI management, link by DLL.
EDIT
Answer was actually given by elgonzo on the comments.
[StructLayout(LayoutKind.Sequential, Pack = 1)]
private struct Packet
{
public byte header;
public byte cmd;
public ushort address;
public ushort len;
public ushort crc;
}
and the GetByte method