container of巨集深度解析

2021-10-02 12:36:52 字數 667 閱讀 3718

作用:

由結構體中某個元素的指標,推出整個結構體變數的指標。

原型:

#define container_of(ptr,type,member)

)變數分析:

ptr指向結構體元素member元素的指標;type為結構體型別;member為結構體中的某個元素;typeof為c語言的關鍵字,用來由變數得到變數的型別,eg;typeof(a)得到變數a的型別。

typeof(((type*)0)->member)* _myptr=(ptr)類似於(int)* p=(ptr)。

巨集解析:

先用typeof得到member元素的型別,定義為乙個指標( _myptr);然後用這個指標減去該元素相對於結構體首位址的偏移量,就得到整個結構體變數的首位址了,再把這個位址強制型別轉換為type*即可(得到指標)。

舉例:

#include

struct mystruct

;#define container_of(ptr,type,member)

)int

main

(viod)

container of巨集定義

1 container of在linux核心中是乙個常用的巨集,用於從包含在某個結構中的指標獲得結構本身的指標,通俗地講就是通過結構體變數中某個成員的首位址進而獲得整個結構體變數的首位址。2 介面 container of ptr,type,member ptr 表示結構體中member的位址 ty...

container of巨集詳解

該巨集位於include linux kernel.h 1.定義格式 define container of ptr,type,member 作用 就是根據乙個結構體變數中的乙個域成員變數的指標來獲取指向整個結構體變數的指標。例 struct demo struct struct demo stru...

Linux 核心巨集 container of

container of ptr,type,member arguments ptrthe pointer to the member.代表指標 type the type ofthe container struct this isembedded in.型別 member 成員變數 the na...