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  。 
 
 
 
 
 
 
 
 
 

转载于:https://www.cnblogs.com/bizhu/p/4101201.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值