Chinaunix首页 | 论坛 | 博客
  • 博客访问: 257449
  • 博文数量: 52
  • 博客积分: 406
  • 博客等级: 一等列兵
  • 技术积分: 549
  • 用 户 组: 普通用户
  • 注册时间: 2012-04-21 12:34
个人简介

......

文章分类

全部博文(52)

文章存档

2014年(1)

2013年(32)

2012年(19)

我的朋友

分类: LINUX

2012-06-16 15:22:20

1. 先来介绍一下 typeof
   typeof 是C语言的新扩展的一个东东,只有部分编译器支持,不过这个特性在linux内核中应用非常广泛.
   typeof的参数可以是两种形式:表达式类型
   type:
   typeof(int *) a,b; 等价于 int *a,*b;  把y定义成x指向的数据类型:typeof(*x) y; 
   expression:
   extern int foo(); typeof(foo()) var;

2. 在看一下#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)

   是获取TYPE类型中成员MEMBER的相对偏移量,如果基址为0,那么地址&((TYPE *)0)->MEMBER转换为size_t后就是此成员的偏移量了这里的0作为起始地址用,来计算偏移量,如果用其它数字代替offsetof得到的数值要减去这个数字才是真正的偏移量,所以这里用0是最佳的选择。

3. 可以看container_of macro 了

   definition:


 

点击(此处)折叠或打开

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


 

   example(http://hi.baidu.com/xiquanlian/blog/item/a070d658642ea482810a18e3.html):

  

点击(此处)折叠或打开

  1. #include <linux/unistd.h>
  2. #include <linux/string.h>
  3. #include <linux/stdlib.h>
  4. #include <linux/kernel.h>

  5. struct cona_t{
  6.     int i;
  7.     int j;
  8.     int v;
  9.     char t[10];
  10.     unsigned short xy;
  11. };


  12. struct cona_t ct;
  13. unsigned short xy;
  14. int main(int argc,char * argv[])
  15. {
  16.     int xy;
  17.     struct cona_t * p;
  18.     memset(&ct,0,sizeof(struct cona_t));
  19.     ct.i = ct.j = ct.v = 10;
  20.     sprintf(ct.t,"%s","sdf");
  21.     ct.xy = 20;
  22.     p = container_of(&ct.xy,struct cona_t,xy);
  23.     
  24.     printf("%s\n",p->t);
  25.     return 0;
  26. }


4. understand & over ....



 







阅读(1880) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~