学无先后,达者为师

网站首页 编程语言 正文

结构体通过成员变量获取主结构体地址(struct)

作者:泰勒朗斯 更新时间: 2022-07-16 编程语言

今天在看代码的时候看到一个巧妙的用法:
两个结构体,一个是V4L2Context,另外一个是V4L2m2mContext;

typedef struct V4L2m2mContext {
    char devname[PATH_MAX];
    int fd;

    /* the codec context queues */
    V4L2Context capture;
    V4L2Context output;

    /* dynamic stream reconfig */
    AVCodecContext *avctx;
    sem_t refsync;
    atomic_uint refcount;
    int reinit;
...
}

如果我们知道其中capture或者output的地址能不能推出来V4L2m2mContext的地址呢,这样就可以V4L2Context少一个指针变量了。
答案是可以的:

#define container_of(ptr, type, member) ({ \
        const __typeof__(((type *)0)->member ) *__mptr = (ptr); \
        (type *)((char *)__mptr - offsetof(type,member) );})

关于其分析:分析

实际使用:

static inline V4L2m2mContext *buf_to_m2mctx(V4L2Buffer *buf)
{
    return V4L2_TYPE_IS_OUTPUT(buf->context->type) ?
        container_of(buf->context, V4L2m2mContext, output) :
        container_of(buf->context, V4L2m2mContext, capture);
}

原文链接:https://blog.csdn.net/weixin_43360707/article/details/125780922

栏目分类
最近更新