A neat feature in C low-level device/network programming is that you can control how a struct
is aligned in memory. So if I know a hardware device will send me binary data in a given format, I can simply copy that raw data into a struct and then access the members, rather than write de-serialization code to populate a POD object by reading each attribute from the received data buffer.
For instance I might receive an 8-byte payload:
- BYTE0: ID (8bit int)
- BYTE1-2: COUNT (16 bit int)
- BYTE3-6: SENSOR-VAL (32 bit float)
- BYTE7: CHECKSUM (8 bit int)
in C I could define my struct
to exactly align its members in memory to this (by default they would be padded for performance reasons) - note this is an example not tested code - so I can copy 8 bytes from an arbitrary byte-buffer into the address of a Msg
object:
#pragma pack(1)
struct Msg {
char ID;
short count;
float sensorVal;
char chk;
};
. In the more abstracted world of C#/.NET, is this possible? If not, is the only solution to manually write low-level deserialization code or can I automate that somehow to save the amount of error-prone code being written?