是否有可能修改该X-宏建立一个结构,它包括阵列? 怎么样?(Is it possible to

2019-08-03 05:19发布

在SO发现这非常有帮助的Q / A: 有,通过在C不同类型的元素一个struct任何方式循环?

但因为我很新的整个X-宏观的东西,我在想,如果和它如何将有可能适应这个例子用数组一个结构 - 就像这样:

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]);

Answer 1:

你已经有了一个良好的开端...

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

(此代码,作为一个单一的文件处理,已知的是GCC 4.7.1下顺利地编译在Mac OS X 10.7.5。)



文章来源: Is it possible to modify this X-Macro to build a struct, which includes arrays? How?