有什么办法来控制C ++结构成员(包括位域)之间的填充? [英] Is there any way to control the padding between struct members (incl. bit field) in C++?

查看:164
本文介绍了有什么办法来控制C ++结构成员(包括位域)之间的填充?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm working on parsing network data stream, I'm wondering if there is any way I can map the data stream directly to the data structure.

例如,我想定义一个RTP协议的数据结构如下:

For example, I want to define the data structure for an RTP protocol as follows.

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 ++编译器会插入成员之间的填充,有没有什么办法来控制所以没有填充的成员之间增加(包括位字段成员)?

But as the C++ compiler will insert padding between the members, is there any way to control that so that no padding are added between members (including the bit field members)?

这问题不是<一个副本href=\"http://stackoverflow.com/questions/3277842/how-to-get-rid-of-padding-bytes-between-data-members-of-a-struct\">How摆脱一个结构的数据成员之间填充字节,因为可以有位域在我的例子。

This question is NOT a duplicate of How to get rid of padding bytes between data members of a struct because there can be bit fields in my example.

推荐答案

只要你有没有要求,这code作品,在任意设备 - 例如已采取限制措施,以什么字节边界机器的 INT 坐在(通常是4字节边界),然后用

As long as you have no requirement that this code "works" on arbitrary machines - e.g. machines that have restrictions as to what byte boundaries an int sits on (typically a 4 byte boundary), then using

 #pragma(pack)

应该工作,它在GCC 支持以及微软和微软插上兼容的编译器(如英特尔的编译器)。

should work, and it's supported in GCC as well as Microsoft and "Microsoft plug in compatible" compilers (Such as Intel's compiler).

但做的注意,不支持在所有处理器上的未对齐访问,因此开始与16位值 INT 块,接着是32位,可能会会导致问题。

But do note that unaligned access is not supported on all processors, so starting a block with a 16-bit value, followed by a 32-bit int is possibly going to cause problems.

我也将使用一个大小为整数来的sequenceNumber确保它在每个编译器的32位,而不是突然16位或64位。

I would also use a sized integer for sequencenumber to ensure it's 32-bits in EVERY compiler, and not suddenly 16 or 64 bits.

还要注意的是C ++标准没有规定有关,该位存储在一个位域的顺序什么 - 或者就此而言,如果它们之间存在与否的差距。尽管可以期望位域按字节顺序存储(小端机器的最低位先开始,大端机器启动最高序位第一),标准没有规定这方面的东西。

Note also that the C++ standard does not state anything about the order that the bits are stored in a bitfield - or for that matter if there are gaps between them or not. Although you can expect the bitfields to be stored according to the byte-order (little endian machines start with the lowest bits first, big endian machines start with the highest order bits first), the standard does not state anything in that respect.

这篇关于有什么办法来控制C ++结构成员(包括位域)之间的填充?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆