结构体成员偏移量,标准C其实有定义宏实现今天看书了解到,坛子里已经不止一次有人提到这个问题了
#undef offsetof#ifdef __compiler_offsetof
#define offsetof(TYPE,MEMBER) __compiler_offsetof(TYPE,MEMBER)
#else
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
#endif
#define __compiler_offsetof(a,b) __builtin_offsetof(a,b)
头文件<stddef.h>,Linux的实现使用的是GCC扩展,比自己手工定义更简单,也可能更快些不错。回复 #1 雨过白鹭洲 的帖子这是什么意思啊????回复 #1 雨过白鹭洲 的帖子linux2.6版本以后用的才是GCC的扩展吧,反正2.4的我看还是标准做法顺便贴一下通过结构体成员求出整个结构体的方法,内核中的代码:
/**
* 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) );})这个是C标准库定义http://www.cially.com/的吧?
貌似跟Linux八竿子都打不上的.
这个是我VC 8.0的offsetof宏.
#ifdef_WIN64
#define offsetof(s,m) (size_t)( (ptrdiff_t)&reinterpret_cast<const volatile char&>((((s *)0)->m)) )
#else
#define offsetof(s,m) (size_t)&reinterpret_cast<const volatile char&>((((s *)0)->m))
#endif原帖由 egmkang 于 2008-11-8 22:33 发表 http://bbs3.chinaunix.net/images/common/back.gif
这个是C标准库定义http://www.18fdg.com/的吧?
貌似跟Linux八竿子都打不上的.
这个是我VC 8.0的offsetof宏.
#ifdef_WIN64
#define offsetof(s,m) (size_t)( (ptrdiff_t)&reinterpret_cast((((s *)0)->m)) )
#else
#define...
你这个是C++的。。呵呵,其实LZ和我贴的都是Linux内核中的实现方法很多人都喜欢自己实现一下,看起来挺吊的:mrgreen:原帖由 gawk 于 2008-11-9 10:31 发表 http://bbs3.chinaunix.net/images/common/back.gif
很多人都喜欢自己实现一下,看起来挺吊的:mr