什么是"包装"结构用C? [英] What is a "packed" structure in C?

查看:189
本文介绍了什么是"包装"结构用C?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要去,虽然一些C code的Microchip C30编译器笔试和我经常看到定义结构如下:

I am going though some C code written for the Microchip C30 compiler and I often see structs defined as follows:

typedef struct __attribute__((__packed__)) 
{
    IP_ADDR     MyIPAddr;               // IP address
    IP_ADDR     MyMask;                 // Subnet mask
    IP_ADDR     MyGateway;              // Default Gateway
        // etc...
} APP_CONFIG;

这是什么意思包装?

What does packed mean?

推荐答案

在定义的结构,编译器不允许添加垫(空格没有实际的数据),使成员陷入地址边界更易于访问的CPU

When structures are defined, the compiler is allowed to add paddings (spaces without actual data) so that members fall in address boundaries that are easier to access for the CPU.

例如,一个32位CPU上,32位成员应该是为了多4个字节被有效地访问(读取和写入)地址启动。以下结构定义将两个部件之间的16位填充,使得第二构件落在正确地址边界

For example, on a 32-bit CPU, 32-bit members should start at addresses that are multiple of 4 bytes in order to be efficiently accessed (read and written). The following structure definition adds a 16-bit padding between both members, so that the second member falls in a proper address boundary:

struct S {
    int16_t member1;
    int32_t member2;
};

在32位架构在上述结构的内存结构( =填充):

+---------+---------+
| m1 |~~~~|   m2    |
+---------+---------+

当结构已压缩,这些补白不插入。编译器生成更code(运行速度较慢)提取不结盟数据成员,也写信给他们。

When a structure is packed, these paddings are not inserted. The compiler has to generate more code (which runs slower) to extract the non-aligned data members, and also to write to them.

的相同的结构,包装时,会出现在内存中是这样的:

The same structure, when packed, will appear in memory as something like:

+---------+---------+
| m1 |   m2    |~~~~
+---------+---------+

这篇关于什么是"包装"结构用C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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