Linux内核源码学习之typeof、offsetof和container_of宏

       在学习Linux内核链表list.h时,遇见了两个很特别的宏定义,它们就是鼎鼎大名的offsetof和container_of宏。本文将分四部分介绍,第一部分介绍typeof,第二部分介绍offsetof宏,第三部分介绍container_of宏,第四部分展示这两个宏的使用代码示例。

一、typeof

       typeof并不是ISO/IEC 9899:1999里的,也就是说不是标准C的运算符,这是gcc的一个扩展。在gcc的官方文档中单独列了一章来说明(可参考http://gcc.gnu.org/onlinedocs/gcc-4.6.2/gcc/Typeof.html#Typeof)。typeof运算符返回一个用来表示表达式的数据类型的字符串。可能的字符串有int、char等。示例程序如下所示: 

int  i;
char *c;

typeof(i) j; // 相当于int j;
typeof(c) p; // 相当于char *p;

二、offsetof宏

       offsetof宏定义如下所示:

#define offsetof(type, member) ((size_t) &((type*)0)->member)

       offsetof宏的功能:获取结构成员在结构中的地址偏移量。member是结构成员名,type是结构名。该宏的实现原理是将0强制转换为type类型的指针,编译器认为0是一个type类型指针指向的有效地址。随后通过该指针索引至member并取出member的地址。由于该指针指向的地址为0,所以 member的地址即为member在type中的地址偏移量。                                  

三、container_of宏

       container_of宏定义如下所示:

#define container_of(ptr, type, member) ({          \
            const typeof( ((type *)0)->member ) *__mptr = (ptr);    \
            (type *)( (char *)__mptr - offsetof(type,member) );})

       container_of宏的功能:通过一个结构体中某个成员的指针得到指向这个结构体的指针。ptr是结构成员指针,type是结构名,member是结构成员名。container_of宏由两部分实现:

(1)const typeof( ((type *)0)->member ) *__mptr = (ptr);                                                                                                                            

       该语句定义了一个member类型的指针变量__mptr,并将ptr赋值给__mptr。此句的作用是检查参数ptr是否为结构体type成员member类型的指针!如果类型不符合,编译器将报错!

(2)(type *)( (char *)__mptr - offsetof(type,member) );

       该语句先将__mptr转化为char型指针(目的是char型指针加减运算是按1个字节移动的!),然后用__mptr(该成员的指针)减去该成员在结构中的地址偏移量,得到结构体的首地址,最后将运算结果转化为type类型指针,即得到指向结构体的指针。

 四、示例代码

#include <stdio.h>
#include <stdlib.h>

struct fox {
    unsigned long tail_length;
    unsigned long weight;
    unsigned char is_fantastic;
};

#define offsetof(type, member) ((size_t) &((type*)0)->member)

#define container_of(ptr, type, member) ({          \
            const typeof( ((type *)0)->member ) *__mptr = (ptr);    \
            (type *)( (char *)__mptr - offsetof(type,member) );})

int main()
{
    printf("tail_length offset: %u\n", offsetof(struct fox, tail_length));
    printf("weight offset: %u\n", offsetof(struct fox, weight));
    printf("is_fantastic offset: %u\n", offsetof(struct fox, is_fantastic));

    struct fox sfox  = { 10, 20, 1};
    struct fox *pfox = container_of(&sfox.is_fantastic, struct fox, is_fantastic);
    printf("tail_length: %u\n", pfox->tail_length);
    printf("weight: %u\n", pfox->weight);
    printf("is_fantastic: %u\n", pfox->is_fantastic);

    return 0;
}

 程序运行结果如图所示:

 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值