****************************************
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编译器所特有的。