如何在用户空间使用container_of宏

****************************************
container_of(pointer,container_type,container_field);
这个宏需要一个container_field字段的指针,该字段包含在container_type类型的结构中,然后返回包含该字段的结构指针。
*****************************************
但由于是在驱动中实现的这个宏,有没有办法在用户空间测试呢?
有的。我们可以将linux/kernel.h头文件包含进来,直接在用户空间测试这个宏的巧妙之处。

下面就是我的测试代码。


main.c文件
#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)


如果打开kernel.h文件,就会发现这个container_of这个宏定义如下:
#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编译器所特有的。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值