首先,为了解决这个问题,您需要知道封闭结构的类型StructType和成员的名称member.那一定是给定的.没有它,问题就没有解决方案.
其次,我不知道为什么其他答案坚持重新发明轮子(并在其上进行未定义和不可移植的黑客攻击),而不是使用标准offsetof宏.随着offsetof答案
StructType *pstruct =
(StructType *) ((char *) pmember - offsetof(StructType, member));
Run Code Online (Sandbox Code Playgroud)
Linux内核代码(GPLv2许可)包括一个方便的container_of()宏:
#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type,member) );})
Run Code Online (Sandbox Code Playgroud)
它是这样使用的:
static inline struct ext3_inode_info *EXT3_I(struct inode *inode)
{
return container_of(inode, struct ext3_inode_info, vfs_inode);
}
Run Code Online (Sandbox Code Playgroud)
@理查德的答案非常好; 主要区别在于此代码被参数化以接受任何struct和任何成员,因此相应地更复杂.