什么是"包装"结构用C?

编程入门 行业动态 更新时间:2024-10-26 13:19:34
本文介绍了什么是"包装"结构用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?

本文发布于:2023-05-25 10:57:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/226656.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:结构   QUOT

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!