代码之家  ›  专栏  ›  技术社区  ›  Marc

如何从指向结构成员的指针以可移植的方式计算指向结构开头的指针?

  •  0
  • Marc  · 技术社区  · 6 年前

    假定 T1 T2 是两种类型,并给出以下结构:

    struct s
    {
      T1 x;
      T2 y;
    }
    

    此外,假设我们有一个类型为的对象 struct s :

    struct s a;
    

    由此,我们可以计算指向对象的第二个结构成员的指针:

    T2 *q = &s.y;
    

    我要找的是一种便携式的计算方法 q 指针 p 类型的 struct s * 这样 指向对象 a .

    3 回复  |  直到 6 年前
        1
  •  4
  •   Eric Postpischil    6 年前

    鉴于 T2 *q = &s.y; 然后 char *x = (char *) q - offsetof(struct s, y); 定义 x 指向的第一个字节 s . 这个 offsetof 宏在中定义 <stddef.h> .

    人们可能会期待 struct s *p = (struct s *) x; 定义一个 p 那指向 S 这取决于一个人希望如何理解C标准。(指针转换为 char 对于指向结构的指针,它是标准未显式定义的第一个字节。我们可以将指针在C 2018 6.3.2.3 7中转换回其原始类型的标准规范作为本例的覆盖。)我希望它可以在所有正常的C实现中工作。

        2
  •  1
  •   ensc    6 年前

    你在找 container_of() Wikipedia

    #define container_of(ptr, type, member) ((type *)((char *)(1 ? (ptr) : &((type *)0)->member) - offsetof(type, member)))
    

    或者更简单,但更不安全

    #define container_of(ptr, type, member) ((type *)((char *)(ptr) - offsetof(type, member)))
    

    在你的情况下,你会像

    struct *s = container_of(q, struct s, y);
    
        3
  •  -1
  •   0___________    6 年前
    T2 *py = &z.y
    
    T1 *px = (T1 *)((char *)py - ((char *)&z.y - (char *)&z.x));
    
    推荐文章