帮助2 C宏

Jak*_*édl 0 c macros struct

我已经定义了2个宏:

#define HCL_CLASS(TYPE) typedef struct TYPE { \
                          HCLUInt rc; \
                          void (*dealloc)(TYPE*);

#define HCL_CLASS_END(TYPE) } TYPE; \
TYPE * TYPE##Alloc() { TYPE *ptr = (TYPE *)malloc(sizeof(TYPE)); if (ptr != NULL) ptr->rc = 1; return ptr; }
Run Code Online (Sandbox Code Playgroud)

这些宏的目的是创建一个带有一些预定义成员(保留计数和解除分配器)函数的C结构,并自动创建一个分配器函数.

现在,当我使用这些宏时:

HCL_CLASS(Dummy)
int whatever;
HCL_CLASS_END(Dummy)
Run Code Online (Sandbox Code Playgroud)

他们扩展到这个(直接取自XCode):

typedef struct Dummy { HCLUInt rc; void (*dealloc)(Dummy*);

int whatever;

} Dummy; Dummy * DummyAlloc() { Dummy *ptr = (Dummy *)malloc(sizeof(Dummy)); if (ptr != ((void *)0)) ptr->rc = 1; return ptr; }
Run Code Online (Sandbox Code Playgroud)

当我尝试编译时,我得到两个错误:

  • 在线上调用HCL_CLASS的''''''''''''''''''''''''''''''''
  • "预期';' 在'int'之前"在线上声明int结构成员

我看不出这些错误的原因.如果你帮我找到它,我将不胜感激.谢谢.

Hea*_*utt 5

您需要使用struct作为参数dealloc,而不是typedef:

#define HCL_CLASS(TYPE) typedef struct _##TYPE { \
                          HCLUInt rc; \
                          void (*dealloc)(struct _##TYPE*);  
                       /* use struct here ^^^^^^, not the typedef */

#define HCL_CLASS_END(TYPE) } TYPE; \
TYPE * TYPE##Alloc() { TYPE *ptr = (TYPE *)malloc(sizeof(TYPE));\
                       if (ptr != NULL) ptr->rc = 1; return ptr; }
Run Code Online (Sandbox Code Playgroud)

这是因为你声明的typedef不完整dealloc.

此外,在C++中,您的结构名称和typedef不得相互冲突.所以我在结构名称中加了一个下划线_##TYPE.