c++ - 有什么方法可以控制 C++ 中结构成员(包括位字段)之间的填充?

标签 c++ c padding

我正在解析网络数据流,我想知道是否有任何方法可以将数据流直接映射到数据结构。

例如,我想定义一个RTP协议(protocol)的数据结构如下。

class RTPHeader
{
   int version:2; // The first two bits is version.
   int P:1;  // The next bits is an field P.
   int X:1;
   int CC:4;
   int M:1;
   int PT:7;
   int sequenceNumber;
   int64 timestamp;
   .....
};

并以这种方式使用它。

RTPHeader header;
memcpy(&header, steamData, sizeof(header));

但是由于 C++ 编译器会在成员之间插入填充,有没有什么办法可以控制成员之间不添加填充(包括位字段成员)?

此问题与 How to get rid of padding bytes between data members of a struct 不重复因为在我的示例中可能存在位域。

最佳答案

如果您能够使用 C++11,则可以利用 alignof 实现的对齐控制。运算符。

如果您不能使用 C++11 编译器,可以使用非标准替代方案来帮助您;在 GCC 中,__attribute__(packed) , 和 MSVC 的 #pragma pack .

如果您选择的是 GCC 变体,则该属性必须放在 结构的末尾:

class RTPHeader
{
    int version:2; // The first two bits is version.
    int P:1;  // The next bits is an field P.
    int X:1;
    int CC:4;
    int M:1;
    int PT:7;
    int sequenceNumber;
    int64 timestamp;
    .....
} __attribute__((packed)) ; // attribute here!

如果您选择的是 MSVC,则编译指示必须放在 结构之前:

#pragma pack(1) // pragma here!
class RTPHeader
{
    int version:2; // The first two bits is version.
    int P:1;  // The next bits is an field P.
    int X:1;
    int CC:4;
    int M:1;
    int PT:7;
    int sequenceNumber;
    int64 timestamp;
    .....
};

如果您的代码必须同时编译,唯一的方法(没有 C++11 alignof 运算符)是条件编译:

#ifdef MSVC
#pragma pack(1)
#endif
class RTPHeader
{
    int version:2; // The first two bits is version.
    int P:1;  // The next bits is an field P.
    int X:1;
    int CC:4;
    int M:1;
    int PT:7;
    int sequenceNumber;
    int64 timestamp;
    .....
#ifdef GCC
}__attribute__((packed));
#else
};
#endif

关于c++ - 有什么方法可以控制 C++ 中结构成员(包括位字段)之间的填充?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18653110/

相关文章:

C程序查询彩票号码: why some tests fail?

c - 如何在C中设置整数的最低有效位

java - 如何删除 android TimePicker 周围的空间

c++ - 在 Windows 7 下编译的 Dll 在 Windows XP 下不起作用

c++ - 存在 Windows 时未找到 Python.h

c++ - 为没有继承的模板参数类提供构造函数

java - 具有完整 GIF 支持的 GIF 文件创建库

c - 为什么这两段简单的代码会给出不同的结果?

css - 正在应用填充,但与 CSS 中的值不同

css - :before, :填充之后