简体   繁体   English

当我们在结构内部有一个指针时,container_of宏

[英]container_of macro when we have a pointer inside a struct

If I have: 如果我有:

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

If I have the pointer ss through which I can access the members inside some_struct, I should be able to access my_container by doing the following right ? 如果我有指针ss,可以通过它访问some_struct内的成员,则应该可以通过执行以下权限来访问my_container? This is what I am doing: 这就是我在做什么:

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

But this is not working for sure and I am not able to comprehend why. 但这不能肯定地起作用,我无法理解原因。 Can someone help me with this? 有人可以帮我弄这个吗? Is there something that I am missing ? 我有什么想念的吗?

If you only have a pointer to some_struct (ie if you just have struct some_struct *ss; ), you cannot use the container_of macro in this way, as &ss will just evaluate to the address of some variable, not the address of my_container . 如果仅具有指向some_struct的指针(即,如果您具有struct some_struct *ss; ),则不能以这种方式使用container_of宏,因为&ss只会求值某个变量的地址, 而不是 my_container的地址。 To use it properly, you'll need a pointer to a pointer to some_struct (ie struct some_struct **pss ). 为了正确使用它,您需要一个指向some_struct的指针(即struct some_struct **pss )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM