前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >编译器特性 _attribute__((packed))

编译器特性 _attribute__((packed))

作者头像
iOS Development
发布2019-02-14 17:44:51
2.2K0
发布2019-02-14 17:44:51
举报

问题

在2016年4月份做项目的时候遇到过一个问题。

从BLE(低功耗蓝牙)设备上收到数据(16进制的数据流),<840100ec d5045715 00010014 00240018 00>,17个bytes(字节),然后我定义了一个结构体去接数据:

代码语言:javascript
复制
typedef struct {
    UInt8 cmd;
    UInt16 index; // 目标:接到0x0100
    UInt32 timeStamp; // 目标:接到0xECD50457
    UInt16 steps;// 目标:接到0x1500
    UInt16 calories;// 目标:接到0x0100
    UInt16 distance;// 目标:接到0x1400
    UInt16 sleep;// 目标:接到0x2400
    UInt16 duration;// 目标:接到0x1800 (一共17 bytes)
} D2MHistoryDataPort;

如果这样去接数据,index接到是0xEC00(目标是0x0100),导致后面的也都全部错位了。为什么会这样?

当时问尽朋友,问尽Google,都没有找到解决的办法。最后硬着头皮,用蹩脚的英语在StackOverFlow进行了第一次提问How to convert NSData to struct accurately(不久还因为问题表达不清被关闭(囧)——幸好在问题关闭前有人已经明白,并给了解决问题的回答)

当时可以解决问题的答案是:

代码语言:javascript
复制
typedef struct __attribute__((packed)) {
    UInt8 cmd;
    UInt16 index;
    UInt32 timeStamp;
    UInt16 steps;// 步数
    UInt16 calories;// 卡路里
    UInt16 distance;// 距离,单位m
    UInt16 sleep;// 睡眠
    UInt16 duration;// 运动时长,单位minute
} D2MHistoryDataPort;

可以看到,多了__attribute__((packed))这部分。当时copy了答案,能work,也没有多深究,忙着去赶项目进度了。

后来也一直在用这招,凡是结构体中用到非UInt8的,都会加上__attribute__((packed))——否则接的时候,都会「错位」。

最近写得多了,「百无聊赖」之下又止不住自己的好奇心:为什么要这样写?

编译器的特性

我们先看看下面两个结构体的定义:

代码语言:javascript
复制
typedef struct __attribute__((packed)) {
    UInt8 cmd;
    UInt16 index;
} D2MCommand;

typedef struct {
    UInt8 cmd;
    UInt16 index;
} D2MCommandNoAttribute;

一个有__attribute__((packed)),一个没有。

再用sizeof()打印他们的长度:

代码语言:javascript
复制
NSLog(@"D2MCommand长度: %@", @(sizeof(D2MCommand)));
NSLog(@"D2MCommandNoAttribute长度: %@", @(sizeof(D2MCommandNoAttribute)));

// 打印结果
D2MCommand长度: 3
D2MCommandNoAttribute长度: 4

定义的数据一样,为什么长度会不一样?

其实是编译器在「作祟」。

为了提高系统性能,CPU处理内存时,会用「数据对齐(Data alignment)」这种方式。这种方式下,数据在内存中都以固定size保存。而为了进行对齐,有时候就需要在数据中插入(data structure padding)一些无意义的字节。比如编译器是以4个bytes为单位对齐的,当你声明一个UInt8的数据,后面就会补齐3个无意义的bytes。

参考:

Data alignment means putting the data at a memory offset equal to some multiple of the word size, which increases the system's performance due to the way the CPU handles memory.

To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.

更详细可参考:What is the meaning of “attribute((packed, aligned(4))) ”

__attribute__

而要改变编译器的对齐方式,就要利用到__attribute__关键字,它是用于设置函数属性(Function Attribute)、变量属性(Variable Attribute)、类型属性(Type Attribute)。也可以修饰结构体(struct)或共用体(union)。

写法为__attribute__ ((attribute-list)),后面的attribute-list大概有6个参数值可以设置:aligned, packed, transparent_union, unused, deprecatedmay_alias(我自己没有全部试过)。

packed

packed属性的主要目的是让编译器更紧凑地使用内存。

所以再回头看__attribute__((packed)),它的作用就是告诉编译器:取消结构体在编译过程中的优化对齐,按尽可能小的size对齐——也就是按1字节为单位对齐。

__attribute__((packed))__attribute__((packed, aligned(1)))是等价的。(aligned(x)就是告诉编译器,以x个字节为单位进行对齐,x只能是1,或2的幂)。

现在就可以解释刚刚打印结果的不一样的原因了:第一个结构体,用__attribute__((packed))取消了在编译阶段的优化对齐,返回的是实际占用字节数。而第二个结构体,由于优化对齐的存在,UInt8的cmd,后面会补(padding)一个byte去对齐,最后加起来就是4个byte了,后面的数据也会错乱。

Conclusion

因此,保险的做法,iOS开发中,如果定义指令,用到非UInt8的数据类型(如UInt16, UInt32),结构体尽量用__attribute__((packed))修饰,防止数据因为对齐而导致的错位。

References

深入剖析 iOS 编译 Clang LLVM

编译器

GCC中的aligned和packed属性

性能优化,要懂点编译原理

黑魔法attribute((cleanup))

ATTRIBUTE 你知多少?

神奇的attribute

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.01.30 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 问题
  • 编译器的特性
    • __attribute__
      • packed
      • Conclusion
      • References
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档