Linux核心鏈表中的宏

來源:互聯網
上載者:User

/* list_entry - get the struct for this entry

  * @ptr: the &struct list_head pointer.

  * @type: the type of the struct this is embedded in.

  * @member: the name of the list_struct within the struct.*/

  #define list_entry(ptr, type, member) ((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member)))

我們使用list_entry()宏在linux鏈表中訪問鏈表資料。

  原理為指標ptr指向結構體type中的成員member;通過指標ptr,返回結構體type的起始地址。

  定義中((size_t) &(type *)0)->member)意為:把0地址轉化為type結構的指標,然後擷取該結構中member成員的指標,並將其強制轉換為size_t類型

&((type *)0)->member:

  把“0”強制轉化為指標類型,則該指標一定指向“0”(資料區段基址)。因為指標是“type *”型的,所以可取到以“0”為基地址的一個type型變數member域的地址。那麼這個地址也就等於member域到結構體基地址的位移位元組數。

  ((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member))):

  (char *)(ptr)使得指標的加減操作步長為一位元組,(unsigned long)(&((type *)0)->member)等於ptr指向的member到該member所在結構體基地址的位移位元組數。二者一減便得出該結構體的地址,轉換為 (type *)型的指標。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.