Linux程序员

由Linux内核链表宏container_of引发

2019-01-03  本文已影响4人  DyadicQ

在探究Linux内核链表的过程中引发了一些疑问:

#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)

/**
 * container_of - cast a member of a structure out to the containing structure
 * @ptr:    the pointer to the member.
 * @type:   the type of the container struct this is embedded in.
 * @member: the name of the member within the struct.
 */
#define container_of(ptr, type, member) ({          \
    const typeof(((type *)0)->member) * __mptr = (ptr); \
    (type *)((char *)__mptr - offsetof(type, member)); })

struct list_head {
  struct list_head *next, *prev;
};
struct my_list{
  int a;
  int b;
  struct list_head list_node;
};

说回到上述的两宏:

//初始化链表
list_head *pos = &(x->list_node);
INIT_LIST_HEAD(head);//略
struct my_list *tmp = container_of(pos, struct my_list, node_list);
tmp->a;
tmp->b;

container_of 第一部分
const typeof(((type *)0)->member)* __mptr = (ptr);

1、typeof是GNU C对标准C的扩展,它的作用是根据变量获取变量类型,typeof也是利用了编译器在编译期计算得到的。
2、typeof获取了type结构体的member成员的变量类型,然后定义了一个指向该变量类型的指针__mptr,并将实际结构体该成员变量的指针的值赋值给__mptr。
3、通过这行代码,临时变量__mptr中保存了type结构体成员变量member在内存中分配的地址值。
container_of 第二部分
(type*)((char*)__mptr - offsetof(type, member));
这块代码是利用__mptr的地址,减去type结构体成员member相对于结构体首地址的偏移地址,得到的自然是结构体首地址,即该结构体指针。

到这里大致解释了这个宏的原理及用法,这里我注意到container_of的第二句为什么要将__mptr转换为(char *)再减去偏移量呢,这里有些莫名奇妙,为什么偏偏是(char *)而不是其他类型。

然而进一步研究发现,这里其实转型成(void *)也是没问题的,但是其他类型就不行。其实这里涉及到最基本的问题,不同类型指针在进行加减运算时地址跨越的字节数是不一样的。
例如:int *a; a++;在64位系统中是a地址向后挪了4个字节而不是1个字节,字节是计算机存储数据的最基本单元,地址的增减就是按最小的粒度字节增减的,换句话说地址间的差值就是差的字节数。
那么这里用(char *)其实是因为(char)恰好是一个字节的长度,也就是最小粒度。而且(void *)是默认的一字节粒度,所以这里的困惑就此解开:

__mptr转型成(char *)类型的指针目的只不过是想让该地址以单字节的粒度进行偏移的加减。

注:测试环境 >>gcc 4.4

上一篇 下一篇

猜你喜欢

热点阅读