【linux内核】container_of

/**
 * 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) );})

container_of - 将结构体的成员强制转换到包含结构体
@ptr:指向成员的指针。
@type:被嵌入的容器结构体的类型。
@member:结构中成员的名称。

例:

struct cm_id_private 
{
	struct ib_cm_id	id;
    ... ...
}


int ib_send_cm_req(struct ib_cm_id *cm_id, struct ib_cm_req_param *param)
{
	struct cm_id_private *cm_id_priv;
    ... ...
	cm_id_priv = container_of(cm_id, struct cm_id_private, id);
    ... ...
}

cm_id是struct cm_id_private的成员id,运行container_of后返回cm_id所在的struct cm_id_private地址。

参考:

C语言offsetof用法以及其扩展用法___builtin_offsetof_lyx_wmt的博客-CSDN博客

C语言typeof详解_致守的博客-CSDN博客

container_of的用法_Alone_悟空的博客-CSDN博客

你可能感兴趣的:(C语言,linux内核,编程,linux,c语言)