【发布时间】:2012-11-13 17:35:04
【问题描述】:
在 SO 上发现了这个非常有用的问答:Is there any way to loop through a struct with elements of different types in C?
但是由于我对整个 X-Macro 的东西还很陌生,所以我想知道,是否以及如何将这个示例用于带有数组的结构 - 像这样:
typedef struct
{
uint8 Addr1[SIZEOF_ADDR];
uint8 Addr2[SIZEOF_ADDR];
uint8 Addr3[SIZEOF_ADDR];
} TEST;
这是要适应的:
//--- first describe the structure, the fields, their types and how to print them
#define X_FIELDS \
X(int, field1, "%d") \
X(int, field2, "%d") \
X(char, field3, "%c") \
X(char *, field4, "%s")
//--- define the structure, the X macro will be expanded once per field
typedef struct {
#define X(type, name, format) type name;
X_FIELDS
#undef X
} mystruct;
我的出发点是这样的,但我很确定,格式必须是别的东西,或者必须被替换:
#define X_FIELDS \
X(uint8, Addr1, "%02X") \
X(uint8, Addr2, "%02X") \
X(uint8, Addr3, "%02X")
地址类似于 {0x10,0x12,0x0A} - 大小相同。
编辑:
这是我目前如何使用这个结构的一个例子,没有 x-macros:
TEST test = {{0x16,0xA4,0x3},
{0x16,0xA4,0x2},
{0x16,0xA4,0x1}};
printf("%02X",test.addr1[i]);
【问题讨论】: