strongswan INIT

在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

記錄一下,以免再爲了這個宏折騰。 

  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章