Chinaunix首页 | 论坛 | 博客
  • 博客访问: 406528
  • 博文数量: 73
  • 博客积分: 3120
  • 博客等级: 中校
  • 技术积分: 785
  • 用 户 组: 普通用户
  • 注册时间: 2010-10-20 12:26
文章分类

全部博文(73)

文章存档

2013年(4)

2012年(10)

2011年(32)

2010年(27)

分类: LINUX

2010-11-23 10:15:34

在include/linux/kernel.h 里有如下声明:
#ifndef offsetof
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
#endif
这里offsetof(TYPE,MEMBER)指获取MEMBER在TYPE中的偏移量
#ifndef container_of
/**
 * container_of - cast a member of a structure out to the containing structure
 * @ptr:    the pointer to the member.
 * @type:    the type of the container struct this is embedded in.
 * @member:    the name of the member within the struct.
 *
 */
#define container_of(ptr, type, member) ({            \
    const typeof(((type *)0)->member) * __mptr = (ptr);    \
//定义member类型的指针__mptr,并赋初值为ptr.
    (type *)((char *)__mptr - offsetof(type, member)); })
//member的地址ptr-它在Type中的偏移,即得到type结构体本身的入口地址
//由结构体type中的成员member的地址ptr,得到包含该Member的Type实例的地址
#endif

Example:

struct MTYPE{
    int a;
    int b;
    int member;
}
struct MTYPE mtype;
container_of(&mtype->member, struct MTYPE, member)得到&mtype

#ifndef max
#define max(x, y) ({                \
    typeof(x) _max1 = (x);            \
//定义与x同类型的_max1并赋值为x
    typeof(y) _max2 = (y);            \
    (void) (&_max1 == &_max2);        \
//这行代码是用来做类型检查的。当比较的两个数类型不一致的时候,会产生warning: comparison of distinct pointer types lacks a cast
    _max1 > _max2 ? _max1 : _max2; })
#endif

关于Typeof有如下定义:

Typeof (alternately typeof or TypeOf) is an provided by several which determines the of a given . This can be useful when constructing parts of programs that need to accept many types of data but may need to take different action depending on the type of data provided.

In languages that support and , the typeof operator can have one of two distinct meanings when applied to an . In some languages, such as , the typeof operator returns the of the object. That is, it tells the program what the true, original type of the object is, irrespective of any type casting. In these languages, the typeof operator is the method for obtaining .

In other languages, such as or and some nonstandard extensions to and , the typeof operator returns the of the object. That is, it tells the program what type the object is declared to be at that point in the program, irrespective of its original form. These languages usually have other constructs for obtaining run-time type information, such as .


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