linux中container_of

來源:互聯網
上載者:User

linux中container_of(ptr, type, member)宏的作用是傳入結構體類型type的域member地址ptr,返回該結構體變數的首地址,定義如下:

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

 

這個宏裡面有2處事GNU C專屬的特性:

1:typeof(x)的意思是取x的類型,GNU C支援而ANSI C不支援

2:GNU C把包含在括弧裡的複合陳述式看做是一個運算式,稱為語句運算式,它可以出現在任何允許運算式的地方。我們可以在語句運算式中使用原本只能在複合陳述式中使用的迴圈變數、局部變數等

例如int aa = ({3; 43-5;});使用不支援GNU C的編譯器會報錯,而使用gcc會得到aa為38
利用GNU C的這種特性,我們可以避免一些宏定義產生副作用,如使用

#define min_t(type,x,y) \
                ({type __x=(x); type __y=(y);__x<__y?__x:__y})
代替

#define min(x,y) ((x)<(y)?(x):(y))
可避免傳入min(a++,b++)產生副作用

 

下面具體分析這個container_of的實現:

1:const typeof( ((type *)0)->member ) *__mptr = (ptr);定義一個和member相同類型的變數__mptr,並把member地址賦給它

 

2:#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
宏的作用是傳入結構體類型TYPE和其中的域MEMBER,返回該域在結構體中的位移地址

 

3:(type *)( (char *)__mptr - offsetof(type,member) );得到結構體的首地址,並強制轉換成type*類型

 

 

測試程式如下:
#include <stdio.h>

#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) );})

typedef struct CONTAIN_s
{
 char a;
 int b;
 char c[10];
}CONTAIN_t;

int main(void)
{
 CONTAIN_t *pcon;
 CONTAIN_t con = {'3', 4, "abc"};
 pcon = container_of(&con.b, CONTAIN_t, b);

 printf("addr &con %p, addr pcon %p\n", &con, pcon);

 return 0;
}

輸出:addr &con 0xbfd4bad8, addr pcon 0xbfd4bad8

typeof關鍵字的用法

http://www.cublog.cn/u3/101356/showart_2081601.html

轉載來自:

http://rookieubuntu.blog.sohu.com/179419212.html

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.