【发布时间】:2020-02-16 08:51:18
【问题描述】:
我知道使用 reinterpret_cast 将 unsigned char 数组强制转换为结构指针可能会导致问题,因为不同系统上的字节填充和排序(如本例所示)
struct SomeData
{
unsigned char first;
int second;
};
unsigned char data[5];
// SomeData might be more than 5 bytes because of padding
// We can't be sure second is valid, because of bytes ordering
SomeData* someData = reinterpret_cast<SomeData*>(data);
但我的问题是针对只有 unsigned char 成员的结构
struct RGB
{
unsigned char r;
unsigned char g;
unsigned char b;
};
unsigned char data[3];
RGB* rgbData = reinterpret_cast<RGB*>(data);
在这种情况下,struct RGB 相当于 unsigned char[3],因此我假设不会有填充。我用g++和msvc测试过,没有加padding,有保证吗?
【问题讨论】:
-
请注意,该结构可能有一些对齐/填充。
-
使用 GCC,您可以通过
__attribute__((packed))强制不填充