linux kernel container_of 的使用,结构体成员数组的形式

#include <stdio.h>

#ifdef offsetof
#undef offsetof
#endif
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)   
#ifdef container_of
#undef container_of
#endif
#define  container_of(ptr, type, member) ({\
    const typeof( ((type *)0)->member ) *__mptr = (ptr);\
    (type *)( (char *)__mptr - offsetof(type,member) );})    

struct test_struct {
    int num;
    char ch;
    float f1;
};

struct test_struct_array { 
    char ch;
    char ch_1;
    int num;
    char ch_2;
    float f1;
    struct test_struct sa[3];
};


struct test_struct_pointer { 
    int num;
    struct test_struct *sp;
};

int main(void) 
{
    struct test_struct *test_struct_1;
    struct test_struct init_struct ={12,'a',12.3};
    char *ptr_ch_1 = &init_struct.ch;
    test_struct_1 = container_of(ptr_ch_1,struct test_struct,ch);
    printf("test_struct_1 =%p  &init_struct = %p\n",test_struct_1,&init_struct);
    printf("test_struct_1->ch =%c\n",test_struct_1->ch);

    struct test_struct_array *test_struct_a_1;
    struct test_struct *sa = NULL;
    struct test_struct_array test_struct_a_test = {'a','b',6,'c',1.22
    ,12,'e',12.3
    ,3,'f',3.3
    ,8,'g',8.3
    };
    sa = &test_struct_a_test.sa[1];
    test_struct_a_1 = container_of(sa,struct test_struct_array,sa[1]);
    printf("test_struct_a_1 =%p  &test_struct_a_test = %p\n",test_struct_a_1,&test_struct_a_test);
    printf("test_struct_a_1->ch_1 =%c test_struct_a_1.sa[1].ch=%c\n",test_struct_a_1->ch_1,test_struct_a_1->sa[1].ch);

    struct test_struct *st = &init_struct;
    struct test_struct_pointer test_struct_p = {4,st};
    struct test_struct_pointer *test_s_p = container_of(&test_struct_p.sp, struct test_struct_pointer, sp);
    printf("test_s_p = %p test_s_p->num = %d &test_struct_pointer = %p\n",test_s_p,test_s_p->num,&test_struct_p);
    return 0;
}

测试结果

$ ./test.exe
test_struct_1 =0xffffcbcc  &init_struct = 0xffffcbcc
test_struct_1->ch =a
test_struct_a_1 =0xffffcb90  &test_struct_a_test = 0xffffcb90
test_struct_a_1->ch_1 =b test_struct_a_1.sa[1].ch=f
test_s_p = 0xffffcb80 test_s_p->num = 4 &test_struct_pointer = 0xffffcb80

正常来说我们使用container_of 的情况都是通过一个结构体成员指针然后获取其所在的结构体的指针,但是有的时候内部是一个数组,通过不同的数组指针获取到其所在的结构体指针(container_of只能是其成员,而不能说成员的成员)

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值