Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Linux核心container_of宏原理解析

container_of是Linux核心中常見的巨集,用於從結構體成員的指標反推出父結構體的指標。

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

它的運作原理是:先取得member的型別,將ptr轉型為member指標,再減去member在type中的offsetof偏移量,最後得到type的起始位址。

例如已知子結構tmp在父結構test中的偏移量為5,若tmp的位址是0x30005646,則父結構test的位址就是0x30005646減去5,也就是0x30005641。

Copyright © Linux教程網 All Rights Reserved