contain_of宏定义
生活随笔
收集整理的這篇文章主要介紹了
contain_of宏定义
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
?Container_of在Linux內(nèi)核中是一個常用的宏,用于從包含在某個結(jié)構(gòu)中的指針獲得結(jié)構(gòu)本身的指針,通俗地講就是通過結(jié)構(gòu)體變量中某個成員的首地址進而獲得整個結(jié)構(gòu)體變量的首地址。
?
實現(xiàn)方式:
container_of(ptr, type, member)?;
?
?? 其實它的語法很簡單,只是一些指針的靈活應(yīng)用,它分兩步:
? ? 第一步,首先定義一個臨時的數(shù)據(jù)類型(通過typeof( ((type *)0)->member )獲得)與ptr相同的指針變量__mptr,然后用它來保存ptr的值。
? ? 第二步,用(char *)__mptr減去member在結(jié)構(gòu)體中的偏移量,得到的值就是整個結(jié)構(gòu)體變量的首地址(整個宏的返回值就是這個首地址)。
? ? 其中的語法難點就是如何得出成員相對結(jié)構(gòu)體的偏移量?
? ?
?
通過例子說明,如清單1:
1 #include <stdio.h> 2 #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER) 3 #define container_of(ptr, type, member) ({ \ 4 const typeof( ((type *)0)->member ) *__mptr = (ptr); \ 5 (type *)( (char *)__mptr - offsetof(type,member) );}) 6 struct test_struct { 7 int num; 8 char ch; 9 float f1; 10 }; 11 int main(void) 12 { 13 struct test_struct *test_struct; 14 struct test_struct init_struct ={12,'a',12.3}; 15 char *ptr_ch = &init_struct.ch; 16 test_struct = container_of(ptr_ch,struct test_struct,ch); 17 printf("test_struct->num =%d\n",test_struct->num); 18 printf("test_struct->ch =%c\n",test_struct->ch); 19 printf("test_struct->ch =%f\n",test_struct->f1); 20 return 0; 21 }?
轉(zhuǎn)載于:https://www.cnblogs.com/linhaostudy/p/7966081.html
總結(jié)
以上是生活随笔為你收集整理的contain_of宏定义的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: FastDFS FAQ (欢迎反馈,我将
- 下一篇: 三、K3 Cloud 开发插件《K3 C