linux驱动中container_of宏定义解释

container_of的用法是,通过结构体成员变量地址获取结构体首地址,以便访问其他变量。

container_of的原型定义在include/linux/kernel.h文件中,内容如下

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

“__”表示内部使用。”__mptr”是中间变量。

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

相关新闻

联系我们

029-89197679

技术咨询:support@i2som.tech

商务合作:market@i2som.tech

工作时间:周一至周五,9:30-18:30,节假日休息