简体   繁体   English

C ++ struct alignment问题

[英]C++ struct alignment question

I have a predefined struct (actually several) where variables span across 32-bit word boundary. 我有一个预定义的结构(实际上是几个),其中变量跨越32位字边界。 In Linux (and Windows using GCC) I am able to get my structs to pack to the correct size using 'attribute((packed))'. 在Linux(以及使用GCC的Windows)中,我能够使用'attribute((packed))'将我的结构打包到正确的大小。 However I cannot get it to work the same way using VC++ and #pragma pack. 但是我无法使用VC ++和#pragma pack以相同的方式工作。

Using GCC this returns a correct size of 6 bytes: 使用GCC,返回正确的6字节大小:

struct
{
    unsigned int   a                : 3;
    unsigned int   b                : 1;
    unsigned int   c                : 15;
    unsigned int   troubleMaker     : 16;
    unsigned short padding          : 13;
} __attribute__((packed)) s;

Using VC++ this returns an incorrect size of 8 bytes 使用VC ++,这将返回不正确的8字节大小

#pragma pack(push)
#pragma pack(1)

struct
{
    unsigned int   a                : 3;
    unsigned int   b                : 1;
    unsigned int   c                : 15;
    unsigned int   troubleMaker     : 16;
    unsigned short padding          : 13;
} s;

#pragma pack(pop)

I can get things to work by splitting 'troubleMaker' across the boundary manually but I'd prefer not to. 我可以通过手动将“troubleMaker”分割成边界来实现工作,但我不愿意。 Any ideas? 有任何想法吗?

Crazy idea: just write a C99 or C++03 -conforming program in the first place 疯狂的想法:首先编写一个符合C99或C ++ 03的程序


I would suggest not using vendor-specific C language extensions to match device or network bit formats. 我建议不要使用特定于供应商的C语言扩展来匹配设备或网络位格式。 Even if you get the fields to line up using a series of one-per-vendor language extensions, you still have byte order to worry about, and you still have a struct layout that requires extra instructions to access. 即使您使用一系列每个供应商的语言扩展来排列字段,您仍然需要担心字节顺序,并且您仍然需要一个需要额外指令才能访问的结构布局。

You can write a C99 conforming program that will work on any architecture or host and at maximum speed and cache efficiency by using the standardized C API string and memory copy functions and the Posix hton and ntoh functions. 您可以使用标准化的C API字符串和内存复制函数以及Posix hton和ntoh函数编写符合C99标准的程序,该程序可以在任何体系结构或主机上以最高速度和缓存效率运行。

A good practice is to use the following functions for which there exist published standards: 一个好的做法是使用已发布标准的以下函数:

C99: memcpy(), Posix: htonl(), htons(), ntohl(), ntohs()

Update: here is some code that should work the same everywhere. 更新:这里有一些代码应该在任何地方都一样。 You may need to get <stdint.h> from this project if Microsoft still hasn't implemented it for C99, or just make the usual assumptions about int sizes. 如果Microsoft 仍然没有为C99实现它,或者只是对int size做出通常的假设,那么你可能需要从这个项目中获取<stdint.h>

#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <stdio.h>
#include <arpa/inet.h>

struct packed_with_bit_fields {  // ONLY FOR COMPARISON
    unsigned int   a        : 3;
    unsigned int   b        : 1;
    unsigned int   c        : 15;
    unsigned int   troubleMaker : 16;
    unsigned short padding  : 13;
} __attribute__((packed));       // USED ONLY TO COMPARE IMPLEMENTATIONS

struct unpacked { // THIS IS THE EXAMPLE STRUCT
    uint32_t a;
    uint32_t b;
    uint32_t c;
    uint32_t troubleMaker;
}; // NOTE NOT PACKED

struct unpacked su;
struct packed_with_bit_fields sp;
char *bits = "Lorem ipsum dolor";

int main(int ac, char **av) {
  uint32_t x;   // byte order issues ignored in both cases

  // This should work with any environment and compiler
  memcpy(&x, bits, 4);
  su.a = x & 7;
  su.b = x >> 3 & 1;
  su.c = x >> 4 & 0x7fff;
  memcpy(&x, bits + 2, 4);
  su.troubleMaker = x >> 3 & 0xffff;

  // This section works only with gcc
  memcpy(&sp, bits, 6);
  printf( sp.a == su.a
      &&  sp.b == su.b
      &&  sp.c == su.c
      &&  sp.troubleMaker == su.troubleMaker
      ? "conforming and gcc implementations match\n" : "huh?\n");
  return 0;
}

Alignment and ordering of bitfields are notoriously implementation-specific. 位域的对齐和排序是众所周知的特定于实现的。 It is much safer to declare a normal integer field and manipulate the "bitfields" within using masks and bitwise (| & ^) operators . 它是安全声明一个正常的整型字段,并使用口罩和位内操纵“位域”(|&^)运营商。

I don't believe this behavior is supported in Visual Studio. 我不相信Visual Studio中支持此行为。 In addiction to the pack macro I tried using __declspec(align(1)) and got the same behavior. 在对包宏的依赖中,我尝试使用__declspec(align(1))并获得了相同的行为。 I think you are stuck with 12 bytes or re-ordering your structure a bit. 我认为你被困在12个字节或者重新排序你的结构。

我相信VC ++不支持这一点,我对GCC在这方面的行为是否实际上是标准的表示严重怀疑。

如果绝对确定需要6个字节然后将其定义为3个短路并自己获取数据...它不会减慢速度......编译器就是这样做...

Shorter example with only conforming code 只有符合规范的代码的较短示例


struct unpacked {  // apparently my other example was too long and confusing
    uint32_t a;    // ...here is a much shorter example with only the conforming
    uint32_t b;    // ...code. (The other program had the gcc-specific declaration,
    uint32_t c;    // but only for test code. Still, it was a bit long.)
    uint32_t troubleMaker;
};

struct unpacked su;
char *bits = "Lorem ipsum dolor";

void f(void) {
  uint32_t x;

  memcpy(&x, bits, 4);
  su.a = x & 7;
  su.b = x >> 3 & 1;
  su.c = x >> 4 & 0x7fff;
  memcpy(&x, bits + 2, 4);
  su.troubleMaker = x >> 3 & 0xffff;
  return 0;
}

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

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