Liuw's Thinkpad

想要赢就先学会输,想要成功就先学会失败

container_of

with 3 comments

#define container_of(p,t,n) (t*)((p)-&(((t*)0)->n))

再来看看Linux Kernel中的实现。

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

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

© 2009, liuw. All rights reserved.

Written by liuw

December 1st, 2009 at 10:47 pm

Posted in Programming

Tagged with , , ,

3 Responses to 'container_of'

Subscribe to comments with RSS or TrackBack to 'container_of'.

  1. 我在想((t*)0)->n)成立嘛? 0×0下怎么会有n这个值?

      (Quote)

    wayne

    2 Dec 09 at 08:23

  2. @wayne
    这个是C语言里面的一个小技巧。上面是我自己实现的版本,Linux Kernel里面的实现估计会好一点。
    一般人印象里面0就是一个“非法地址”,其实不应该这样理解。C语言是很自由的,什么地址做怎么样的解释,完全是程序员个人的自由。注意,是“解释”,我们并不需要这个地址上真的存在一个语义上合法的值。

      (Quote)

    liuw

    2 Dec 09 at 11:14

  3. 理解,就和( *(void (*)( ) ) 0)( )一样

      (Quote)

    wayne

    6 Dec 09 at 18:22

Leave a Reply

*