2012-11-19 59 views
5

的定义,而不是定义container_of为:的container_of宏观

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

为什么不会这只是工作:

#define container_of(ptr, type, member) ({ \ 
        (type *)((char *)(ptr) - offsetof(type,member));}) 

什么是第一线的定义中的使用情况如何?

回答

7

它增加了一些类型的安全级别。使用你的第二个版本,我可以通过任何东西进行ptr,它会很好地编译。使用内核版本,如果您传递的ptr的指针与type.member的类型不匹配,您至少会收到警告。