新闻中心

EEPW首页 > 嵌入式系统 > 设计应用 > linux内核中的typeof

linux内核中的typeof

作者: 时间:2016-11-22 来源:网络 收藏
内核版本:2.6.14

今天分析内核时又看到了typeof,只知道它大概是返回变量的类型,后来上网查了下发现这个关键字在linux中用的非常多。如果你对sizeof很熟悉的话,那么大可进行类推,sizeof(exp)返回的是exp的数据类型大小,那么typeof(exp.)返回的就是exp的数据类型。下面是linux内核中typeof的一些例子。

本文引用地址:https://www.eepw.com.cn/article/201611/319991.htminclude/linux/kernel.h
[plain]view plaincopy
print?
  1. /*
  2. *min()/max()macrosthatalsodo
  3. *stricttype-checking..Seethe
  4. *"unnecessary"pointercomparison.
  5. */
  6. #definemin(x,y)({
  7. typeof(x)_x=(x);//_x的数据类型和x一样
  8. typeof(y)_y=(y);
  9. (void)(&_x==&_y);
  10. _x<_y?_x:_y;})
  11. #definemax(x,y)({
  12. typeof(x)_x=(x);
  13. typeof(y)_y=(y);
  14. (void)(&_x==&_y);
linux/include/asm-arm/uaccess.h
[plain]view plaincopy
print?
  1. #defineget_user(x,p)
  2. ({
  3. constregistertypeof(*(p))__user*__pasm("r0")=(p);//__p的数据类型和*(p)的指针数据类型是一样的,__p=p
  4. registertypeof(*(p))__r2asm("r2");//__r2的数据类型和*(p)的数据类型是一样的
  5. registerint__easm("r0");
  6. switch(sizeof(*(__p))){
  7. case1:
  8. __get_user_x(__r2,__p,__e,1,"lr");
  9. break;
  10. case2:
  11. __get_user_x(__r2,__p,__e,2,"r3","lr");
  12. break;
  13. case4:
  14. __get_user_x(__r2,__p,__e,4,"lr");
  15. break;
  16. case8:
  17. __get_user_x(__r2,__p,__e,8,"lr");
  18. break;
  19. default:__e=__get_user_bad();break;
  20. }
  21. x=__r2;
  22. __e;
  23. })
下面写一个小程序示例一下:
[plain]view plaincopy
print?
  1. #include
  2. typedefstruct
  3. {
  4. intx;
  5. chary;
  6. }astruct,*pastrcut;
  7. intmain()
  8. {
  9. intsizem,sizew;
  10. intx=3;
  11. typeof(&x)m=&x;
  12. sizem=sizeof(m);
  13. *m=5;
  14. typeof(((astruct*)5)->y)w;
  15. sizew=sizeof(w);
  16. w="a";
  17. return1;
  18. }

首先看main函数里的m变量,这个变量的类型就是typeof(&x), 由于x是int型的(这里与x是否被赋值一点关系都没有),所以&x应该是int *类型,那么typeof(&x)返回的类型就是int*,所以m自然也就是个int*类型的。

然后我们看w变量,其类型是 typeof(((astruct *)5)->y), 其中astruct是一个被定义的结构类型,其中的y元素是char类型,那么((astruct *)5)->y是啥意思呢?在这里5并不是真正的变量,可以把它理解为一个替代使用的符号,当然这个符号最好是一个数,其意思更可以理解为一个被赋值了的变量,这个数可以是0,3,也可以是8也可以随便什么都可以。那么((astruct *)5)->y仅仅就是表示了y这个变量,所以typeof的结果就是y元素的类型,也就是char。



关键词: linux内核typeo

评论


技术专区

关闭