在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
記錄一下,以免再爲了這個宏折騰。