如何在用户空间使用container_of宏
来源:互联网 发布:人力资源优化配置方案 编辑:程序博客网 时间:2024/05/21 20:23
****************************************
container_of(pointer,container_type,container_field);
这个宏需要一个container_field字段的指针,该字段包含在container_type类型的结构中,然后返回包含该字段的结构指针。
*****************************************
但由于是在驱动中实现的这个宏,有没有办法在用户空间测试呢?
有的。我们可以将linux/kernel.h头文件包含进来,直接在用户空间测试这个宏的巧妙之处。
下面是Makefile文件
CC=gcc
TAR=main
SRC=main.c
KERNEL_INCLUDE ?= /lib/modules/$(shell uname -r)/build/include
all:
$(CC) -D__KERNEL__ -o $(TAR) -I$(KERNEL_INCLUDE) $(SRC)
clean:
#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type,member) );})
offsetof又被如下定义:
#ifdef __KERNEL__
#undef offsetof
#ifdef __compiler_offsetof
#define offsetof(TYPE,MEMBER) __compiler_offsetof(TYPE,MEMBER)
#else
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
#endif
那个__compiler_offsetof原型是__builtin_offsetof这个是GCC编译器所特有的。
container_of(pointer,container_type,container_field);
这个宏需要一个container_field字段的指针,该字段包含在container_type类型的结构中,然后返回包含该字段的结构指针。
*****************************************
但由于是在驱动中实现的这个宏,有没有办法在用户空间测试呢?
有的。我们可以将linux/kernel.h头文件包含进来,直接在用户空间测试这个宏的巧妙之处。
下面就是我的测试代码。
#include <linux/unistd.h>#include <linux/string.h>#include <linux/stdlib.h>#include <linux/kernel.h>struct cona_t{ int i; int j; int v; char t[10]; unsigned short xy;};struct cona_t ct;unsigned short xy;int main(int argc,char * argv[]){ int xy; struct cona_t * p; memset(&ct,0,sizeof(struct cona_t)); ct.i = ct.j = ct.v = 10; sprintf(ct.t,"%s","sdf"); ct.xy = 20; p = container_of(&ct.xy,struct cona_t,xy); printf("%s\n",p->t); return 0;}
下面是Makefile文件
CC=gcc
TAR=main
SRC=main.c
KERNEL_INCLUDE ?= /lib/modules/$(shell uname -r)/build/include
all:
$(CC) -D__KERNEL__ -o $(TAR) -I$(KERNEL_INCLUDE) $(SRC)
clean:
rm -f $(TAR)
#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type,member) );})
offsetof又被如下定义:
#ifdef __KERNEL__
#undef offsetof
#ifdef __compiler_offsetof
#define offsetof(TYPE,MEMBER) __compiler_offsetof(TYPE,MEMBER)
#else
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
#endif
那个__compiler_offsetof原型是__builtin_offsetof这个是GCC编译器所特有的。
- 如何在用户空间使用container_of宏
- 在用户空间程序也使用container_of()
- 用户空间如何使用i2c_dev
- container_of宏使用分析
- 如何在Linux里面限制用户空间
- 通过sysfs在用户空间使用GPIO
- 通过sysfs在用户空间使用GPIO
- 在FreeBSD 用户空间与内核空间使用内存共享
- linux 内核中的container_of()如何使用
- 如何在linux内核中调用用户空间的程序
- 如何在linux内核中调用用户空间的程序
- 如何在linux内核中调用用户空间的程序
- 如何在linux内核中调用用户空间的程序
- 如何在linux内核中调用用户空间的程序
- 如何在内核中读取用户空间数据
- linux 在用户空间如何实现usb热插拔
- windbg 如何在内核模式调试用户空间的程序
- 如何在QQ空间中使用背景图片
- HDFS的架构要点
- 处理 HttpURLConnection的字符流中文乱码
- Windows 上 postgresql VC 工程的搭建
- 从搜索引擎优化(seo)到社交媒体优化(smo)
- Delphi 编写COM+组件的知识和样例
- 如何在用户空间使用container_of宏
- 投影时出现错误ERROR 999999: Error executing function.
- GB2312 字符集
- PHP
- 阿里巴巴面试总结
- android代码库之textview跑马灯效果
- C#与java的比较
- GBin1分享:25个超酷手绘插图的网站设计
- 黑马程序员_String对象