问题描述
我与一些分组数据的工作。我创建结构来保存数据包。这些结构已经被巨蟒所产生的特定网络协议。
I am working with some packet data. I have created structs to hold the packet data. These structs have been generated by python for a specific networking protocol.
的问题是,由于编译器对齐的结构中,当我经由网络协议发送数据的事实,该消息最终被超过我想。这会导致其它设备无法识别该命令。
The issue is that due to the fact that the compiler aligns the structures, when I send the data via the networking protocol, the message ends up being longer than I would like. This causes the other device to not recognize the command.
有谁知道解决这个工作可能让自己的加壳是完全相同的大小结构应该还是有办法,我可以关掉内存对齐?
Does anyone know possible a work around this so that my packers are exactly the size the struct should be or is there a way I can turn off memory alignment?
推荐答案
在GCC,你可以使用 __ __属性((包装))
。这些天GCC支持的#pragma包
了。
In GCC, you can use __attribute__((packed))
. These days GCC supports #pragma pack
, too.
例如:
-
属性
方法:
#include <stdio.h>
struct packed
{
char a;
int b;
} __attribute__((packed));
struct not_packed
{
char a;
int b;
};
int main(void)
{
printf("Packed: %zu\n", sizeof(struct packed));
printf("Not Packed: %zu\n", sizeof(struct not_packed));
return 0;
}
输出:
$ make example && ./example
cc example.c -o example
Packed: 5
Not Packed: 8
杂包
方法:
#include <stdio.h>
#pragma pack(1)
struct packed
{
char a;
int b;
};
#pragma pack()
struct not_packed
{
char a;
int b;
};
int main(void)
{
printf("Packed: %zu\n", sizeof(struct packed));
printf("Not Packed: %zu\n", sizeof(struct not_packed));
return 0;
}
输出:
$ make example && ./example
cc example.c -o example
Packed: 5
Not Packed: 8
这篇关于没有内存对齐与海湾合作委员会的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!