如何获取结构中的成员数量?

0 c structure runtime

我想计算结构中的成员数量。例如:

typedef struct
{
    char    MrChar;
    int MrInt;
    long    MrLong;
} Bg_Typedef;
Bg_Typedef FooStr;
Run Code Online (Sandbox Code Playgroud)

我创建了一个函数原型,它应该返回结构中的成员数

int NumberOfMem(Bg_Typedef *psStructure); 
Run Code Online (Sandbox Code Playgroud)

=> NumberOfMem(&FooStr) 应该返回 3

sma*_*c89 6

可以用X_MACRO's来完成。

做这样的事情:

#define X_BG_MEMBERS \
    X(char, MrChar) \
    X(int, MrInt) \
    X(long, MrLong)

typedef struct {
#define X(type, member) type member;
    X_BG_MEMBERS
#undef X
} Bg_Typedef;

Bg_Typedef FooStr;
Run Code Online (Sandbox Code Playgroud)

定义一个函数来计算成员数。也可以只是一个变量,但要使变量static const不被覆盖

static int
bg_members_count() {
    #define X(_, __) +1
    static int COUNT = 0
    X_BG_MEMBERS;
    #undef X
    
    return COUNT;
}
Run Code Online (Sandbox Code Playgroud)

现在你可以在 main 中做这样的事情:

#include <stdio.h>
...

int main() {
    printf("The number of members defined in Bg_Typedef is %d\n", bg_members_count());
}
Run Code Online (Sandbox Code Playgroud)

你应该得到类似的东西:

The number of members defined in Bg_Typedef is 3
Run Code Online (Sandbox Code Playgroud)

您可能也只想要一个常量,因此您可以执行以下操作

#define X(_, __) +1
static const int COUNT = X_BG_MEMBERS;
#undef X
Run Code Online (Sandbox Code Playgroud)

替代模式

为了避免有很多#define X...后跟#undef X,这样做可能是有益的:

#define X_BG_MEMBERS(X) \
    X(char, MrChar) \
    X(int, MrInt) \
    X(long, MrLong)

#define BG_STRUCT_FIELD(type, field) type field;
#define BG_COUNT_MEMBER(_, __) +1

typedef struct {
  X_BG_MEMBERS(BG_STRUCT_FIELD)
} Bg_Typedefarguably;

static int
bg_members_count() {
    static int COUNT = X_BG_MEMBERS(BG_COUNT_MEMBER);    
    return COUNT;
}

// OR constant
// static const int COUNT = X_BG_MEMBERS(BG_COUNT_MEMBER);
Run Code Online (Sandbox Code Playgroud)

它的工作原理与上述相同,但应该明显更具可读性。见参考