I want to define a data struct which I can access byte wise. In other words: I want to transfer an object of a specific data structure byte wise.
The goal is to have a high level access (access by name) to the data as well as a low level access that is only byte wise.
I do have a data transfer protocol that has a specific packet format (Header, Payload, CRC,... even bit definitions. Eventually the entire packet is 32-bit aligned).
In "C" I define a struct and access an object of this struct byte wise by casting that object into a byte array. I.e.:
/* C-Code */
typedef struct
{
int16_t a;
int8_t b;
/* And a bit-wise definition to make thinks really cool */
int8_t bit_0 : 1;
int8_t bit_1_7 : 7;
/* (Total size is 4 bytes i.e. 32-bit aligned) */
} MY_STRUCT_t;
"my_struct" should now be read byte wise to e.g. transfer it to some where:
The inexpressive way:
/* C-Code */
void main(void)
{
MY_STRUCT_t my_struct;
for(uint32_t i = 0; i < sizeof(my_struct); i++)
{
Transfer_Byte( *((uint8_t *) &my_struct) + i);
}
}
Or to make it more expressive i will define the following "union" as well:
/* C-Code */
typedef union
{
MY_STRUCT_t data;
uint8_t bytes[sizeof(MY_STRUCT_t)];
} MY_STRUCT_u;
and do it this way:
/* C-Code */
void main(void)
{
MY_STRUCT_u my_struct; // object of the union this time!
for(uint32_t i = 0; i < sizeof(my_struct); i++)
{
Transfer_Byte(my_struct.bytes[i]);
}
}
Question
- How do I do this in C#? What is your suggestion? Or could you give me a hint how to solve this?
Cheers