在strongswan中有一个INIT宏,实现方式如下:
// Object allocation/initialization macro, using designated initializer.
#define INIT(this, ...) { (this) = malloc(sizeof(*(this))); \ *(this) = (typeof(*(this))){ __VA_ARGS__ }; }
这个宏是将结构体成员初始化,在调用的时候直接给成员赋值,实例如下:
#include <stdio.h> #include <stdlib.h> #define INIT(this, ...) { (this) = malloc(sizeof(*(this))); \ *(this) = (typeof(*(this))){ __VA_ARGS__ }; } struct yyy { char *name; }; struct xxx { int id; struct yyy public; }; int main(void) { struct xxx *x; INIT(x, .public={ .name="XiaoMing" }, .id=1); printf("id: %d, name: %s\n", x->id, x->public.name); INIT(x, .public={ .name="XiaoHua" }, .id=2); printf("id: %d, name: %s\n", x->id, x->public.name); }
输出结果:
# ./a.out id: 1, name: XiaoMing id: 2, name: XiaoHua
记录一下,以免再为了这个宏折腾。