container_of 例子说明
来源:互联网 发布:mpp 文件查看 mac 编辑:程序博客网 时间:2024/06/11 06:24
很早前之前看的linux内核,一直想把container_of记录一下,趁今天想起就记录一下:
内核中的描述
/**
* container_of - cast a member of a structure out to the containing structure
* @ptr: the pointer to the member.
* @type: the type of the container struct this is embedded in.
* @member: the name of the member within the struct.
*
*/
#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr);\
(type *)( (char *)__mptr - offsetof(type,member) );})
作用:返回member成员对应的所在的父结构体指针。下面的例子就通过child变量的一个成员地址获取到child变量的地址,以便访问child变量的其他成员
#include <stdio.h>#include <stdlib.h>#include <unistd.h>#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)#define container_of(ptr, type, member) ({\const typeof( ((type *)0)->member ) *__mptr = (ptr);\(type *)( (char *)__mptr - offsetof(type,member) );})struct parentStruct{int a; int b;};struct childStruct{struct parentStruct parent;int a; int b;};void main(void){struct childStruct * child =(struct childStruct*) malloc(sizeof(struct childStruct));child->a =100;child->b =1000;child->parent.a =200;child->parent.b =2000;struct parentStruct *parent = &child->parent;struct childStruct * child1 = container_of(parent,struct childStruct,parent);printf("%d,%d\n",child->a,child1->a);printf("%d,%d\n",child->b,child1->b);printf("%d,%d\n",child->parent.a,child1->parent.a);printf("%d,%d\n",child->parent.b,child1->parent.b);printf("%#x,%#x\n",child,child1);free(child);}
阅读全文
0 0
- container_of 例子说明
- 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
- Java常见帮助类(6)JSON帮助类
- JS实现HTML实体与字符的相互转换(一)
- 17 位谷歌 Android 开发专家是如何看待 Kotlin 的?
- Kotlin练习-二分查找
- (转)路由器WAN口IP显示为10、100、172开头,网络被电信联通等运营商做了NAT转发
- container_of 例子说明
- 【算法】堆排序
- 最大m子段和总结与例题 51nod1052
- Python知识点笔记之函数
- 广播接收者
- strace sqlplus
- 如何用Python做词云(收藏)
- Meissel Lehmer Algorithm快速统计前n个元素中所有的质数以及改编(论文题)
- linux Tcp 套接字