offsetof的使用

#include  <stddef.h>
#define  offsetof  (  TYPE ,  m )   ( size_t  )& reinterpret_cast <  const  volatile  char &>(((( TYPE  *)0)-> m ))
宏功能:得到一个结构体变量成员在此结构体中的偏移量。经过获取偏移量取得结构体的地址
 
 
/*  Takes a pointer to a member variable and computes pointer to the structure
    that contains it. 'type' is type of the structure, not the member. */
#define  nn_cont  ( ptr ,  type ,  member  ) \
    ( ptr  ? ((  type *) ((( char  *)  ptr ) -  offsetof ( type  ,  member ))) :  NULL )
 
这个宏是经过知道ptr的地址,这个地址也是member的地址,使用offsetof计算menber的偏移量,ptr-member的偏移量得到
type结构体变量的地址。
 
 
在nanomsg代码中,
   for  (  it  =  nn_list_begin  (& self .  socktypes );
           it  !=  nn_list_end  (& self .  socktypes );
           it  =  nn_list_next  (& self .  socktypes ,  it  )) {
         socktype  =  nn_cont  ( it ,  struct  nn_socktype  ,  item );
        ......
        }
 
     socktypes 是个链表,保存着结构体   nn_socktype 的 item 成员,因此it指向的是成员item的地址,经过item的地址得到
    结构体 nn_socktype 的变量  socktype  。 
相关文章
相关标签/搜索