我试图用结构映射位图文件的标题。看来,编译器做4字节(32位)比对,但我需要2字节。我试图通过编译指令来改变这种状况,如下
的#pragma包(2)
和
__ attribute__((排列(XX)));
这两个似乎没有产生任何影响。是否有另一种方式做到这一点? 我用X code 4.3的Mac OS X狮子。我测试了苹果LLVM和苹果GCC执行者。
下面是结构类型定义
typedef结构{
int16_t bfType;
int32_t bfSize;
int16_t bfReserved1;
int16_t bfReserved2;
int32_t bfOffBits;
int32_t biSize;
int32_t biWidth;
int32_t biHeight;
int16_t双翼飞机;
int16_t biBitCount;
int32_t biComression;
int32_t biSizeImage;
int32_t biXPelsPerMeter;
int32_t biYPelsPerMeter;
int32_t biClrUsed;
int32_t biClrImportant;
} THEADER;
解决方案
咦?作品在我的机器上?请记住,包编译可能是被覆盖在别的地方?
的#include< inttypes.h>
#包括< STDDEF.H>
的#pragma包(推,2)
typedef结构{
int16_t bfType;
int32_t bfSize;
int16_t bfReserved1;
int16_t bfReserved2;
int32_t bfOffBits;
int32_t biSize;
int32_t biWidth;
int32_t biHeight;
int16_t双翼飞机;
int16_t biBitCount;
int32_t biComression;
int32_t biSizeImage;
int32_t biXPelsPerMeter;
int32_t biYPelsPerMeter;
int32_t biClrUsed;
int32_t biClrImportant;
} THEADER;
的#pragma包(POP)
#包括< stdio.h中>
INT主要(无效)
{
的printf(%鲁\ N,对offsetof(THEADER,bfType));
的printf(%鲁\ N,对offsetof(THEADER,bfSize));
的printf(%鲁\ N,对offsetof(THEADER,bfReserved1));
的printf(%鲁\ N,对offsetof(THEADER,bfReserved2));
返回0;
}
$铛-o包pack.c
$ ./pack
0
2
6
8
I'm trying to use struct to map header of a BitMap file. It seems that compiler is doing 4byte (32bit) alignment but I need 2Byte. I tried to change that via complier directive as below
#pragma pack(2)
and
__attribute__ ((aligned(xx)));
those two doesn't seem to have any effect. Is there another way to do this? I'm using XCode 4.3 on Mac OS X Lion. I Tested both Apple LLVM and Apple GCC compliers.
Here is the Struct type definition
typedef struct {
int16_t bfType;
int32_t bfSize;
int16_t bfReserved1;
int16_t bfReserved2;
int32_t bfOffBits;
int32_t biSize;
int32_t biWidth;
int32_t biHeight;
int16_t biPlanes;
int16_t biBitCount;
int32_t biComression;
int32_t biSizeImage;
int32_t biXPelsPerMeter;
int32_t biYPelsPerMeter;
int32_t biClrUsed;
int32_t biClrImportant;
} THeader;
解决方案
Huh? works on my machine? Bear in mind that the pack pragma is possibly being overridden somewhere else?
#include <inttypes.h>
#include <stddef.h>
#pragma pack(push,2)
typedef struct {
int16_t bfType;
int32_t bfSize;
int16_t bfReserved1;
int16_t bfReserved2;
int32_t bfOffBits;
int32_t biSize;
int32_t biWidth;
int32_t biHeight;
int16_t biPlanes;
int16_t biBitCount;
int32_t biComression;
int32_t biSizeImage;
int32_t biXPelsPerMeter;
int32_t biYPelsPerMeter;
int32_t biClrUsed;
int32_t biClrImportant;
} THeader;
#pragma pack(pop)
#include <stdio.h>
int main(void)
{
printf("%lu\n", offsetof(THeader, bfType));
printf("%lu\n", offsetof(THeader, bfSize));
printf("%lu\n", offsetof(THeader, bfReserved1));
printf("%lu\n", offsetof(THeader, bfReserved2));
return 0;
}
$ clang -o pack pack.c
$ ./pack
0
2
6
8