gpt4 book ai didi

c - 是否可以修改此 X-Macro 来构建一个包含数组的结构?如何?

转载 作者:行者123 更新时间:2023-11-30 17:56:23 26 4
gpt4 key购买 nike

发现这个非常有帮助的问答: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 宏:

TEST test =  {{0x16,0xA4,0x3},
{0x16,0xA4,0x2},
{0x16,0xA4,0x1}};

printf("%02X",test.addr1[i]);

最佳答案

你有一个合理的开始......

#include <stdio.h>
typedef unsigned char uint8;
enum { SIZEOF_ADDR = 3 };

#define X_FIELDS \
X(uint8, Addr1, "0x%02X") \
X(uint8, Addr2, "0x%02X") \
X(uint8, Addr3, "0x%02X")

//--- define the structure, the X macro will be expanded once per field
typedef struct {
#define X(type, name, format) type name[SIZEOF_ADDR];
X_FIELDS
#undef X
} TEST;

extern void iterate1(TEST *test);
extern void iterate2(TEST *test);

//--- Print the values
void iterate1(TEST *test)
{
const char *pad;
//--- "iterate" over all the fields of the structure
#define X(type, name, format) \
printf("%s is ", #name); \
pad = "{"; \
for (size_t i = 0; i < sizeof(test->name); i++) \
{ \
printf("%s" format, pad, test->name[i]); \
pad = ","; \
} \
printf("}\n");
X_FIELDS
#undef X
}

// Alternatively, define a function `print_addr()`
static void print_addr(const char *format, const uint8 *addr, size_t addrsize)
{
char pad = '{';
for (size_t i = 0; i < addrsize; i++)
{
putchar(pad);
printf(format, addr[i]);
pad = ',';
}
putchar('}');
}

//--- Print the values using print_addr()
void iterate2(TEST *test)
{
//--- "iterate" over all the fields of the structure
#define X(type, name, format) \
printf("%s is ", #name); \
print_addr(format, test->name, sizeof(test->name)); \
printf("\n");
X_FIELDS
#undef X
}

(此代码被视为单个文件,已知可以在 Mac OS X 10.7.5 上的 GCC 4.7.1 下干净地编译。)

关于c - 是否可以修改此 X-Macro 来构建一个包含数组的结构?如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13561509/

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