循环遍历 C 中结构中的元素以提取单个元素的值和数据类型 [英] Looping through elements in a struct in C for extracting value and datatype of the individual element
问题描述
我有一个要求,我有一个由大约 30 多个不同数据类型的不同元素组成的 C 语言结构:
I have a requirement where I have a big structure in C consisting of around more than 30 different elements of different data types:
typedef struct {
type1 element1;
type2 element2;
type3 element3;
type2 element4[10];
...
typeN elementN;
} my_messg_struct;
这里基本上是通过串行协议发送的消息中的一组元素.该消息具有不同数据类型的各种元素,如上述结构中所捕获.同样,我也有很多其他消息.现在我必须编写一个通用函数,它负责读取这些消息结构并循环读取每个元素的值和数据类型,然后通过串行端口进行传输.我需要先读取数据类型,因为在我的情况下,各种数据类型的传输顺序是不同的.
where this is basically a group of elements in a message sent over the serial protocol. This message has various elements of varying datatypes as captured in the above structure. Similarly, I have a lot of other messages as well. Now I have to write a generic function which is responsible for reading these message structs and loop through each of the elements reading the element's value and datatype and then transmitting over the serial port. I need to read the datatype first because the order of transmission of various datatypes is different in my case.
所以,基本上,我只想知道如何在 C 中循环遍历结构的元素,以便我可以读取结构中存在的每个元素的值和数据类型?
So, basically, I just wanted to know how to loop through elements of a struct in C in such a way that I can read the value and data type of each of the element present in a struct?
推荐答案
您可以尝试使用 X 宏,但由此产生的源代码可读性值得怀疑:
You could try to use X macros, but the resulting source code readability is questionable:
#include <stdio.h>
#define LIST_OF_VARIABLES \
XI(int, value1) \
XD(double, value2) \
XU(unsigned, value3)
#define XI(int, name) int name;
#define XD(double, name) double name;
#define XU(unsigned, name) unsigned name;
typedef struct A {
LIST_OF_VARIABLES
} A;
#undef XI
#undef XD
#undef XU
void print_variables(struct A a)
{
#define XI(type, name) printf("%s = %d\n", #type, a.name);
#define XD(type, name) printf("%s = %f\n", #type, a.name);
#define XU(type, name) printf("%s = %u\n", #type, a.name);
LIST_OF_VARIABLES
#undef XI
#undef XD
#undef XU
}
int main(void) {
A a = {
.value1 = 10,
.value2 = 0.5,
.value3 = 1,
};
print_variables(a);
return 0;
}
既然您在每个 #type
出现处都放置了一个类型字符串,您可以使用一些字符串比较函数来确定每种类型的基础.
Now that you have a type string placed on every #type
occurrence you could use some string comparison functions to determine what to based for each type.
这篇关于循环遍历 C 中结构中的元素以提取单个元素的值和数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!