gpt4 book ai didi

c - 使用 int 或枚举值访问结构字段

转载 作者:行者123 更新时间:2023-12-02 08:00:09 24 4
gpt4 key购买 nike

我目前使用的日志系统使用标记值来标识它将存储的参数。我们使用的格式如下:标签 + 时间 + 值(value)。

下一步是获取记录的消息并将其发送到使用 Protocol Buffers 序列化数据的服务器。

protocol buffer .proto 文件,提供了一个结构体,其中的所有字段都对应于原始日志系统中的一个标签。

当我需要有效地读取标签并将值分配给 Protocol Buffer 结构中的字段时,问题就来了。本质上,例如,我想接受标记 5 并能够在结构中找到字段 5 并写入值。

我知道这可以通过 switch case 来完成,但我们使用了大约 50 个标签,所以我想尽可能避免使用这种解决方案。我附上一个示例结构来说明问题。

/* Struct definitions */
typedef struct _Profiles {
int32_t param1;
int32_t param2;
int32_t param3;
int32_t param4;
int32_t param5;
int16_t param6;
int32_t param7;
uint32_t param8;
int32_t param9;
int32_t param10;
uint32_t param11;
int32_t time;
/* @@protoc_insertion_point(struct:Profiles) */
} Profiles;

预期的结果是我可以存储如下记录的行:5 1345643 1500(标签、时间、值)

到 Protocol Buffer 结构:

profiles.param5 = 1500
profiles.time = 1345643

无需 12 个开关盒(在本例中)。基本上,我如何使用整数/枚举访问结构的第 5 个声明字段。

请记住,结构的每个字段都可能具有不同的类型。

最佳答案

我的方法是使用指向以下每个字段的指针。

int *ptr[11] = {&profiles.param1, &profiles.param2,  &profiles.param3,,,,,, &profiles.param11};

当消息到达时,我将使用 ptr 更新该字段。

  *ptr[tag-1] = 1500; //tag-1 because ptr[4] points to profiles.param5

关于c - 使用 int 或枚举值访问结构字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58339880/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com