关于container_of宏
来源:互联网 发布:seo和sem之间的区别 编辑:程序博客网 时间:2024/05/16 12:26
先看一段代码:
#include <stdio.h>#include <stddef.h>#define container_of(ptr, type, member) ({ \ const typeof(((type *) 0)->member) *__mptr = (ptr); \ (type *) ((char *) __mptr - offsetof(type, member));})#define container_of2(ptr, type, member) ({ \ (type *) ((char *) ptr - offsetof(type, member));})typedef struct stTest stTest;struct stTest{char m1;int m2;char m3;int m4;char m5;int m6;};int main(int argc,char *argv[]){stTest st,*pst;char *p;printf("st= %p\n",&st);p = &(st.m3);printf("p = %p\n",p);pst = container_of(p,stTest,m3);printf("pst= %p\n",pst);pst = container_of2(p,stTest,m3);printf("pst2= %p\n",pst);return 1;}
可能输出如下:
[root@localhost ~]# ./test st= 0xbfef670cp = 0xbfef6714pst= 0xbfef670cpst2= 0xbfef670c
它根据一个结构中一个成员的指针获得了整个结构的指针,不过宏中
const typeof(((type *) 0)->member) *__mptr = (ptr);
这句似乎可有可无。如果有的话,当指针p的类型和结构成员的类型不一致时会出一个警告,没有的话就不会有警告了。
写代码时那两个头文件一定要包含,否则可能会编译不通过。
- 关于container_of宏
- 关于container_of
- 关于container_of等宏的整理
- 关于linux内核container_of宏的理解
- container_of()宏
- container_of()宏
- container_of()宏
- container_of()宏
- container_of()宏
- container_of()宏
- container_of()宏
- container_of()宏
- container_of()宏
- container_of()宏
- container_of()宏
- container_of()宏
- container_of宏
- container_of()宏
- bash下处理包含空格的文件名
- 用GDB调试程序(七)
- 如何使用Visual Studio 2008编译C语言
- VC时间操作
- java socket总决
- 关于container_of宏
- 由pushViewController说起可能出线的各种死法
- 二叉树创建的小总结
- 吐槽一下opencv&xcode
- 英语练习 47 What a ngihtmare!
- JavaScript世界的一等公民 - 函数
- Backup SQLServer 2008 DataBase using PowerShell
- JUnit4基础
- The Linux Kernel API