傳說linux kernel 雖用C寫的,但是寫得很OO,又很有效率,果然不假,裡面用了很多嘆為觀止的程式碼。 真是藝術 只能這樣說。
#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type,member) );})
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
簡單的說,就是在做記憶體的shift從目前的pointer shift到struct的位址
讓你可以操作該struct
這種寫法 我絕對想不出來Orz
//這真是太神奇了 傑克
#define size_t unsigned int
#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type,member) );})
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
struct a{
int ab;
int ac;
};
int main()
{
struct a c;
c.ab = 10;
c.ac = 100;
int *ptr = &c.ab;
struct a *b;
b = container_of(ptr, struct a, ab );
printf("%d", b->ac );
return 0;
}
印出100, 這種東西 , 可以用來把介面抽出來, 並實做在很多資料結構上!
2007年11月22日 星期四
DS
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言