禁用结构填充用C不使用编译 [英] Disable structure padding in C without using pragma

查看:89
本文介绍了禁用结构填充用C不使用编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何用C禁用结构的填充,而不使用编译?

How can I disable structure padding in C without using pragma?

推荐答案

有是这样做的标准方法。该标准规定,填充可在执行的自由裁量权来实现。从C99 6.7.2.1结构和联合说明符,第12段:

There is no standard way of doing this. The standard states that padding may be done at the discretion of the implementation. From C99 6.7.2.1 Structure and union specifiers, paragraph 12:

结构或联合对象的每个非位字段成员在适合其类型实现定义的方式排列。

Each non-bit-field member of a structure or union object is aligned in an implementation-defined manner appropriate to its type.

尽管如此,有几件事情你可以试试。

Having said that, there's a couple of things you can try.

您第一次四折,使用的#pragma 来试图说服编译器不收拾。在任何情况下,这是不可移植的。也不是任何其他特定于实现的方式,但你应该检查到他们,因为它可能需要做,如果你真的需要这种能力。

The first you've already discounted, using #pragma to try and convince the compiler not to pack. In any case, this is not portable. Nor are any other implementation-specific ways but you should check into them as it may be necessary to do it if you really need this capability.

二是为了你的领域中最大到最小的顺序,例如所有的长长类型随后的人,那么所有的 INT 最后字符类型。这通常会工作,因为它是最常见的类型较大具有更严格对齐要求。再次,不便于携带。

The second is to order your fields in largest to smallest order such as all the long long types followed by the long ones, then all the int, short and finally char types. This will usually work since it's most often the larger types that have the more stringent alignment requirements. Again, not portable.

第三,你可以定义你的类型为字符阵列和投的地址,以确保没有填充。但请记住,有些架构会减慢,如果变量没有正确对齐,还有一些人就会失败(如提高总线错误和终止的过程,例如)。

Thirdly, you can define your types as char arrays and cast the addresses to ensure there's no padding. But keep in mind that some architectures will slow down if the variables aren't aligned properly and still others will fail miserably (such as raising a BUS error and terminating your process, for example).

这是最后一个具有一些进一步的解释。假设你有以下顺序领域的结构:

That last one bears some further explanation. Say you have a structure with the fields in the following order:

char C; // one byte
int  I; // two bytes
long L; // four bytes

通过填充,你可以用下面的字节结束:

With padding, you may end up with the following bytes:

CxxxIIxxLLLL

其中, X 是填充。

不过,如果你定义你的结构:

However, if you define your structure as:

typedef struct { char c[7]; } myType;
myType n;

您可以:

CCCCCCC

然后,您可以这样做:

You can then do something like:

int *pInt = &(n.c[1]);
int *pLng = &(n.c[3]);
int myInt = *pInt;
int myLong = *pLng;

给你:

CIILLLL

再次不幸的是,不是便携式的。

Again, unfortunately, not portable.

所有这些解决方案靠,你有你的编译器的深入了解和底层数据类型。

All these "solutions" rely on you having intimate knowledge of your compiler and the underlying data types.

这篇关于禁用结构填充用C不使用编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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