简体   繁体   English

C# vs C:组织数据结构

[英]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).我确实有一个数据传输协议,它具有特定的数据包格式(标头、有效负载、CRC、...甚至位定义。最终整个数据包是 32 位对齐的)。

In "C" I define a struct and access an object of this struct byte wise by casting that object into a byte array.在“C”中,我定义了一个结构并通过将该对象转换为字节数组来逐字节访问该结构的对象。 Ie: 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: “my_struct”现在应该按字节读取,例如将其传输到某个位置:
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#?我如何在 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.对于 C#,您最好实现“ToByte”和“FromByte”函数并直接处理字段以确保以您希望的方式对数据进行排序。

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.我谨慎使用 struct union 技巧,除非您在同一平台上打包和解包并且可执行,因为字节顺序是平台和编译器相关的多字节值。

For the Low-Level access there is a StructLayoutAttribute.Pack Field in conjunction with FieldOffsetAttribute对于低级访问,有一个StructLayoutAttribute.Pack 字段FieldOffsetAttribute结合使用

With these attributes you can manage how bytes are aligned in the structure.使用这些属性,您可以管理字节在结构中的对齐方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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