跳转至

特殊实现

1 container_of

  • 参考
  • 作用:container_of 通过结构体成员变量地址获取这个结构体的地址。
  • 语法:其中关键点是 offsetof 找到成员偏移量
/* Offset of member MEMBER in a struct of type TYPE. */
#define offsetof(TYPE, MEMBER) __builtin_offsetof (TYPE, MEMBER)

/*addr 成员指针
* type 结构体 比如struct Stu
* member 成员变量,跟指针对应
* */
#define container_of(addr, type, member) ({         \
    const typeof(((type *) 0)->member) * __mptr = (addr);   \
    (type *)((char *) __mptr - offsetof(type, member)); })
  • 示例:通过过 s1 的成员 b 的指针推到出 s1 的地址
struct S1
{
    int a;
    double b;
};
struct S1 s1;
double* pb=&s1.b;
struct S1* s2=container_of(pb,struct S1,b);