为什么不应该以这种方式隐藏结构实现呢?

Yan*_*aud 2 c c++

我已经看到一些C/C++代码使用一个技巧来隐藏结构实现使用相同大小的不透明(阴影)结构:

private.h,声明了结构的确切实现:

typedef struct private_struct
{
    private_foo_t f1;
    private_bar_t b[2];
    private_baz_t *bz;
    int val;
} private_t;

#define PRIVATE_SIZE (sizeof(private_t))
Run Code Online (Sandbox Code Playgroud)

public.h,公共结构被声明为包含不透明的字节数组:

#include "private.h"

typedef struct public_struct
{
    char opaque[PRIVATE_SIZE];
} public_t;
Run Code Online (Sandbox Code Playgroud)

public_tprivate_t分享相同的大小.

用户可以使用公共结构为私有实现分配自己的存储:

#include <public.h>

int main(void)
{
    public_t pub;

    return public_api(&pub);
}
Run Code Online (Sandbox Code Playgroud)

实现可以访问隐藏的实现:

#include "private.h"

int public_api(public_t *pub)
{
    private_t *priv = (private_t *) pub;

    return priv->val;
}
Run Code Online (Sandbox Code Playgroud)

这似乎是一个非常巧妙的技巧,允许用户为变量分配存储(例如声明静态变量).

我在各种嵌入式系统上使用这个技巧移植专有源代码,但我对结构pub_t的声明方式没有信心.

这招可能有什么问题?

Yan*_*aud 8

小心对齐!

public_t原生对齐为1,因为char它与1个字节对齐. private_talignment设置为其成员的最高对齐要求,当然不是1.它可能与指针(void *)的大小对齐,但是double在子结构内部可能需要8个字节的对齐.根据ABI,您可能会看到各种对齐方式.

让我们尝试一个示例程序,使用gcc在i386/i686上编译和测试(代码源跟随):

     kind         name       address   size   alignment   required

     type |      foo_t |         N/A |   48 |       N/A |        4 
     type |     priv_t |         N/A |   56 |       N/A |        4 
     type |      pub_t |         N/A |   56 |       N/A |        1 

   object |       u8_0 |  0xfff72caf |    1 |         1 |        1
   object |       u8_1 |  0xfff72cae |    1 |         2 |        1
   object |       u8_2 |  0xfff72cad |    1 |         1 |        1
   object |       pub0 |  0xfff72c75 |   56 |         1 |        1
   object |       u8_3 |  0xfff72c74 |    1 |         4 |        1
   object |       pub1 |  0xfff72c3c |   56 |         4 |        1
   object |       u8_4 |  0xfff72c3b |    1 |         1 |        1
   object |      priv0 |  0xfff72c00 |   56 |      1024 |        4
   object |       u8_5 |  0xfff72bff |    1 |         1 |        1
   object |      priv1 |  0xfff72bc4 |   56 |         4 |        4
   object |       u8_6 |  0xfff72bc3 |    1 |         1 |        1

  pointer |       pubp |  0xfff72c75 |   56 |         1 |        1
  pointer |      privp |  0xfff72c75 |   56 |         1 |        4  **UNALIGNED**
   object | privp->val |  0xfff72c75 |    4 |         1 |        4  **UNALIGNED**
   object | privp->ptr |  0xfff72c79 |    4 |         1 |        4  **UNALIGNED**
   object |   privp->f |  0xfff72c7d |   48 |         1 |        4  **UNALIGNED**
Run Code Online (Sandbox Code Playgroud)

测试的源代码:

#include <stdalign.h>
#ifdef __cplusplus
/* you will need to pass -std=gnu++11 to g++ */
#include <cstdint>
#endif
#include <stdint.h>
#include <stdio.h>
#include <inttypes.h>

#ifdef __cplusplus
#define alignof __alignof__
#endif

#define PRINTHEADER() printheader()
#define PRINTSPACE() printspace()
#define PRINTALIGN(obj) printobjalign("object", #obj, &obj, sizeof(obj), alignof(obj))
#define PRINTALIGNP(ptr) printobjalign("pointer", #ptr, ptr, sizeof(*ptr), alignof(*ptr))
#define PRINTALIGNT(type) printtypealign(#type, sizeof(type), alignof(type))

static void
printheader(void)
{
    printf(" %8s   %10s   %18s   %4s   %9s   %8s\n", "kind", "name", "address", "size", "alignment", "required");
}

static void
printspace(void)
{
    printf(" %8s   %10s   %18s   %4s   %9s   %8s\n", "", "", "", "", "", "");
}

static void
printtypealign(const char *name, size_t szof, size_t alof)
{
    printf(" %8s | %10s | %18s | %4zu | %9s | %8zu \n", "type", name, "N/A", szof, "N/A", alof);
}

static void
printobjalign(const char *tag, const char *name, const void * ptr, size_t szof, size_t alof)
{
    const uintptr_t uintptr = (uintptr_t)ptr;
    uintptr_t mask = 1;
    size_t align = 0;

    /* get current alignment of the pointer */
    while(mask != UINTPTR_MAX) {

        if ((uintptr & mask) != 0) {
            align = (mask + 1) / 2;
            break;
        }

        mask <<= 1;
        mask |= 1;
    }

    printf(" %8s | %10s | %18p | %4zu | %9zu | %8zu%s\n",
           tag, name, ptr, szof, align, alof, (align < alof) ? "  **UNALIGNED**" : "");
}

/* a foo struct with various fields */
typedef struct foo
{
    uint8_t f8_0;
    uint16_t f16;
    uint8_t f8_1;
    uint32_t f32;
    uint8_t f8_2;
    uint64_t f64;
    uint8_t f8_3;
    double d;
    uint8_t f8_4;
    void *p;
    uint8_t f8_5;
} foo_t;

/* the implementation struct */
typedef struct priv
{
    uint32_t val;
    void *ptr;
    struct foo f;
} priv_t;

/* the opaque struct */
typedef struct pub
{
    uint8_t padding[sizeof(priv_t)];
} pub_t;

static int
test(pub_t *pubp)
{
    priv_t *privp = (priv_t *)pubp;

    PRINTALIGNP(pubp);
    PRINTALIGNP(privp);
    PRINTALIGN(privp->val);
    PRINTALIGN(privp->ptr);
    PRINTALIGN(privp->f);
    PRINTSPACE();

    return privp->val;
}

int
main(void)
{
    uint8_t u8_0;
    uint8_t u8_1;
    uint8_t u8_2;
    pub_t pub0;
    uint8_t u8_3;
    pub_t pub1;
    uint8_t u8_4;
    priv_t priv0;
    uint8_t u8_5;
    priv_t priv1;
    uint8_t u8_6;

    PRINTHEADER();
    PRINTSPACE();

    PRINTALIGNT(foo_t);
    PRINTALIGNT(priv_t);
    PRINTALIGNT(pub_t);
    PRINTSPACE();

    PRINTALIGN(u8_0);
    PRINTALIGN(u8_1);
    PRINTALIGN(u8_2);
    PRINTALIGN(pub0);
    PRINTALIGN(u8_3);
    PRINTALIGN(pub1);
    PRINTALIGN(u8_4);
    PRINTALIGN(priv0);
    PRINTALIGN(u8_5);
    PRINTALIGN(priv1);
    PRINTALIGN(u8_6);
    PRINTSPACE();

    return test(&pub0);
}
Run Code Online (Sandbox Code Playgroud)

分析:

pub0在堆栈上分配,并作为参数传递给函数test.它在1个字节上对齐,因此,当作为priv_t指针强制转换时,priv_t结构成员不对齐.

这可能很糟糕:

  • 正确性不好:某些架构/ CPU会无声地破坏对未对齐内存地址的读/写操作,有些则会产生错误.后者更好.
  • 糟糕的性能:如果支持的话,对齐访问/负载/存储仍然已知处理不当:你可能会问到的CPU读/写对象的内存大小的两倍......你可能会严重打击缓存这样.

所以,如果你真的想要隐藏结构内容,你应该注意底层结构的对齐:不要使用char.

默认情况下,使用void *,或者如果可以double在结构的任何成员中使用double.这将有效,直到有人使用#prama__attribute__(())为隐藏结构(的一个成员)选择更高的对齐方式.

让我们正确定义pub_t:

typedef struct pub
{
    double opaque[(sizeof(priv_t) + (sizeof(double) - 1)) / sizeof(double)];
} pub_t;
Run Code Online (Sandbox Code Playgroud)

听起来可能很复杂,而且确实如此!这样,pub_t结构将具有正确的对齐并且至少与底层一样大priv_t.

如果priv_t打包(带#pragma__attribute__(())),使用sizeof(priv_t)/sizeof(double),pub_t可能小于priv_t......这将比我们最初尝试解决的问题更糟糕.但如果结构被打包,谁在乎对齐.

的malloc()

如果pub_t通过malloc()而不是在堆栈上分配来分配结构,则对齐将不是问题,因为malloc()定义为返回与C本机类型的最大存储器对齐对齐的存储器块,例如.double.在现代malloc()实现中,对齐可以达到32个字节.

  • 这涵盖了您将使用此方法看到的可能错误之一。我原以为可维护性是一个更大的问题,因为人们将有用的新字段添加到私有结构中,而忘记将它们添加到公共版本中。 (2认同)
  • `sizeof`不会自动包含填充吗?例如,参见http://ideone.com/fZ7Cuj,其似乎填充到4字节边界. (2认同)