GCC结构内的内存对齐 [英] memory alignment within gcc structs

查看:249
本文介绍了GCC结构内的内存对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将应用程序移植到C中的ARM平台,应用程序也运行在x86处理器上,并且必须是向后兼容的。

I am porting an application to an ARM platform in C, the application also runs on an x86 processor, and must be backward compatible.

我现在有可变对准一些问题。我已阅读GCC手册
__属性__((排列(4),装))我间preT与结构的开始对齐到4字节疆和里面在说什么因为包装的声明保持不变。

I am now having some issues with variable alignment. I have read the gcc manual for __attribute__((aligned(4),packed)) I interpret what is being said as the start of the struct is aligned to the 4 byte boundry and the inside remains untouched because of the packed statement.

原来我有这个,但有时它被放在未对齐的4字节边界。

originally I had this but occasionally it gets placed unaligned with the 4 byte boundary.

typedef struct  
{  
 unsigned int code;  
 unsigned int length;  
 unsigned int seq;  
 unsigned int request;  
 unsigned char nonce[16];  
 unsigned short  crc;  
} __attribute__((packed)) CHALLENGE;

所以我改成这样。

so I change it to this.

typedef struct  
{  
 unsigned int code;  
 unsigned int length;  
 unsigned int seq;  
 unsigned int request;  
 unsigned char nonce[16];  
 unsigned short  crc;  
} __attribute__((aligned(4),packed)) CHALLENGE;

该理解我先前所说似乎是不正确的,这两个结构现在对齐到4字节边界,和现在的内部数据对齐到一个四字节的边界,但由于字节序的,该结构的大小从42到44个字节的尺寸也增加了。这个尺寸是至关重要的,因为我们有依赖于结构为42字节的其他应用程序。

The understand I stated earlier seems to be incorrect as both the struct is now aligned to a 4 byte boundary, and and the inside data is now aligned to a four byte boundary, but because of the endianess, the size of the struct has increased in size from 42 to 44 bytes. This size is critical as we have other applications that depend on the struct being 42 bytes.

能否有人形容我如何执行我需要的操作。任何帮助深表AP preciated。

Could some describe to me how to perform the operation that I require. Any help is much appreciated.

推荐答案

如果你视的sizeof(yourstruct) 42个字节,你即将成为由非便携式假设世界咬伤。你有没有说什么,这是对的,但它很可能是该结构的内容事项的字节顺序一样,所以您可能还与x86存在不匹配了。

If you're depending on sizeof(yourstruct) being 42 bytes, you're about to be bitten by a world of non-portable assumptions. You haven't said what this is for, but it seems likely that the endianness of the struct contents matters as well, so you may also have a mismatch with the x86 there too.

在这种情况下,我认为唯一安全可靠的方式来应对是使用 unsigned char型[42] 在它很重要的部分。写的到底是什么领域在哪里在这42个字节的块precise规范开始,什么尾数,然后用这个定义来写一些code到这一点,你可以用交互的结构之间进行转换。在code将可能是要么全在一次序列化code(又名编组),或一堆getter和setter。

In this situation I think the only sure-fire way to cope is to use unsigned char[42] in the parts where it matters. Start by writing a precise specification of exactly what fields are where in this 42-byte block, and what endian, then use that definition to write some code to translate between that and a struct you can interact with. The code will likely be either all-at-once serialisation code (aka marshalling), or a bunch of getters and setters.

这篇关于GCC结构内的内存对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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