Is it possible to modify this X-Macro to build a struct, which includes arrays? How?

送分小仙女□ 提交于 2019-12-02 08:11:32

You've got a reasonable start...

#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
}

(This code, treated as a single file, is known to compile cleanly under GCC 4.7.1 on Mac OS X 10.7.5.)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!