linux c操作之container_of的使用

  • Post author:
  • Post category:linux


作用:给定结构体中某个成员的地址,该结构体类型和该成员的名字获取这个成员所在

结构体变量的首地址.

当链表通过list串起来的时候,此时并不知道ist1的首地址,反而知道list的地址,这个时候

container_of(),来得到这个结构体变量首地址.

(1)ptr 结构体变量中某个成员的地址 pointer to the member

(2)type:结构体类型 the type of the container struct this is embedded in

(3)member:该结构体类型的具体名字 the name of the member within the struct

/**

  • 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) ({

void *__mptr = (void

)(ptr);

BUILD_BUG_ON_MSG(!__same_type(

(ptr), ((type

)0)->member) &&

!__same_type(

(ptr), void),

“pointer type mismatch in container_of()”);

((type *)(__mptr – offsetof(type, member))); })

应用地方:

struct



版权声明:本文为M_1308347688原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。