【问题标题】:container_of macro when we have a pointer inside a structcontainer_of 宏,当我们在结构中有指针时
【发布时间】:2014-10-30 19:25:42
【问题描述】:

如果我有:

struct my_container {
    int x;
    struct some_struct *ss;
}

如果我有指针 ss 可以通过它访问 some_struct 中的成员,我应该能够通过执行以下操作来访问 my_container 吗? 这就是我正在做的事情:

struct my_container *my_c;
my_c = container_of(&ss, struct my_container, ss)

但这肯定不起作用,我无法理解为什么。 有人可以帮我弄这个吗?有什么我想念的吗?

【问题讨论】:

  • 你说的container_of()是什么意思,它是一个使用过的定义函数吗?
  • @Madan 它是 linux 内核中的一个宏,充当 offsetof 的“逆”
  • 是 container_of 类似于 #define container_of(ptr, type, member) ((type *)((char *)(ptr)-(unsigned long)(&((type *)0)- >成员)))?

标签: c linux pointers struct kernel


【解决方案1】:

如果您只有一个指向some_struct 的指针(即,如果您只有struct some_struct *ss;),则不能以这种方式使用container_of 宏,因为&ss 只会计算到某个变量的地址,不是my_container的地址。要正确使用它,您需要一个指向some_struct 的指针(即struct some_struct **pss)。

【讨论】:

  • 好的。我明白我做错了什么。谢谢!但我现在遇到的问题是,为了获取指向 some_struct 的指针,我正在使用 container_of() 宏。我不确定如何获得指向 some_struct 的指针。有没有办法做到这一点?
  • 表示不使用struct my_container *my_c; my_c = container_of(&ss, struct my_container, ss);你会使用: struct some_struct **my_struct_ptr = &some_struct_ptr; my_c = container_of(&my_struct_ptr, struct my_container, ss); .container_of 的第一个参数是起始地址,而不是结构中的指针。希望这会有所帮助
  • @buzz 我想你的意思是 struct some_struct **my_struct_ptr = &some_struct_ptr; my_c = container_of(my_struct_ptr, struct my_container, ss);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-08
  • 1970-01-01
  • 2011-02-18
  • 2019-07-18
  • 1970-01-01
  • 2011-07-05
  • 1970-01-01
相关资源
最近更新 更多