设为首页 加入收藏

TOP

Linux内核开发:offset宏的讲解
2014-11-24 08:32:21 来源: 作者: 【 】 浏览:1
Tags:Linux 内核 开发 offset 讲解

1.offset宏讲解
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE*)0)->MEMBER)


对这个宏的讲解我们大致可以分为以下4步进行讲解:


1>( (TYPE *)0 ) 0地址强制 "转换" 为 TYPE结构类型的指针;


2>((TYPE *)0)->MEMBER 访问TYPE结构中的MEMBER数据成员;


3>&( ( (TYPE *)0 )->MEMBER)取出TYPE结构中的数据成员MEMBER的地址;


4>(size_t)(&(((TYPE*)0)->MEMBER))结果转换为size_t类型。


宏offsetof的巧妙之处在于将0地址强制转换为 TYPE结构类型的指针,TYPE结构以内存空间首地址0作为起始地址,则成员地址自然为偏移地址。可能有的读者会想是不是非要用0呢?当然不是,我们仅仅是为了计算的简便。也可以使用是他的值,只是算出来的结果还要再减去该数值才是偏移地址。来看看如下的代码:


#include


#defineoffsetof(TYPE, MEMBER) ((size_t) &((TYPE *)4)->MEMBER)


struct test_struct {


int num;


char ch;


float f1;


};


int main(void)


{


printf("offsetof (struct test_struct,num)=%d\n",offsetof(struct test_struct,num)-4);


printf("offsetof (structtest_struct,ch) =%d\n",offsetof(struct test_struct,ch)-4);


printf("offsetof (struct test_struct,f1)=%d\n",offsetof(struct test_struct,f1)-4);


return 0;


}


运行结果为:


jibo@jibo-VirtualBox:~/cv_work/work/list/offset $ ./main


offsetof (struct test_struct,num) =0


offsetof (struct test_struct,ch) =4


offsetof (struct test_struct,f1) =8


为了让大家加深印象,我们在代码中没有使用0,而是使用的4,所以在最终计算出的结果部分减去了一个4才是偏移地址,当然实际使用中我们都是用的是0。


二.举例体会offsetof宏的使用:
#include


#defineoffsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)


struct test_struct {


int num;


char ch;


float f1;


};


int main(void)


{


printf("offsetof(struct test_struct,num) =%d\n",offsetof(struct test_struct,num));


printf("offsetof (structtest_struct,ch) =%d\n",offsetof(struct test_struct,ch));


printf("offsetof (struct test_struct,f1)=%d\n",offsetof(struct test_struct,f1));


return 0;


}


执行结果为:


jibo@jibo-VirtualBox:~/cv_work/work/list/offset $ ./main


offsetof (struct test_struct,num) =0


offsetof (struct test_struct,ch) =4


offsetof (struct test_struct,f1) =8


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Linux内核开发:container_of分析 下一篇.bash_profile .bashrc profile ..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·定义一个类模板并实 (2025-12-27 06:52:28)
·一文搞懂怎么用C语言 (2025-12-27 06:52:25)
·常用C模板范文_百度 (2025-12-27 06:52:21)
·【C语言】动态内存管 (2025-12-27 06:23:20)
·C语言中的内存管理 - (2025-12-27 06:23:16)