简体   繁体   中英

C# vs C: Organizing Data Structures

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. Ie:

/* 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 eg 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

For C# you're best to implement a "ToByte" and "FromByte" function and process the fields directly to ensure that the data is ordered in the manner that you wish.

BTW . I cautious using the struct union trick unless your packing and unpacking on the same platform and executable as the byte order is platform and compiler dependent for multibyte values.

For the Low-Level access there is a StructLayoutAttribute.Pack Field in conjunction with FieldOffsetAttribute

With these attributes you can manage how bytes are aligned in the structure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM