美文网首页iOS Development
编译器特性 _attribute__((packed))

编译器特性 _attribute__((packed))

作者: AntonyWong | 来源:发表于2018-01-30 23:00 被阅读152次

问题

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

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

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(不久还因为问题表达不清被关闭(囧)——幸好在问题关闭前有人已经明白,并给了解决问题的回答)

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

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))——否则接的时候,都会「错位」。

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

编译器的特性

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

typedef struct __attribute__((packed)) {
    UInt8 cmd;
    UInt16 index;
} D2MCommand;

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

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

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

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

相关文章

  • 编译器特性 _attribute__((packed))

    问题 在2016年4月份做项目的时候遇到过一个问题。 从BLE(低功耗蓝牙)设备上收到数据(16进制的数据流),<...

  • OC中的 __attribute__中关于__attribute

    首先__attribute__用于向编译器描述特殊的标识、检查或优化的,等等 而__attribute__((cl...

  • 如何屏蔽Unused variable

    方法一:编译器属性__attribute__ 方法二:全局控制 方法三:#pragma unused() 方法四:...

  • Clang Attributes 黑魔法小记

    编译器属性__attribute__用于向编译器描述特殊的标识、检查或优化,几个常用的用法看《mattt大神的文章...

  • iOS 编译过程的原理和应用

    前言 __attribute__ Clang警告处理 预处理 插入编译期脚本 提高项目编译速度 iOS编译 编译器...

  • 浅谈 __attribute__

    __attribute__ 是一个编译器指令,其实是 GNU C 的一种机制,本质是一个编译器的指令,在声明的时候...

  • __attribute__积累

    来源 __attribute__是GNU C的一大特色,用于辅助编译器。可以设置函数属性、变量属性、类型属性。at...

  • __attribute__

    __attribute__是GCC启用的很有用的编译器指令类似于ISO C的#pragma在LLVM下得到了扩充 ...

  • __attribute__在Objective-C中的运用

    __attribute__机制是GNU C的一大特色,增强编译器的功能,带来更多的检查,更多的优化。可以设置函数特...

  • Ios面试复习--ARC内存管理

    ARC是编译器特性(LLVM3.0编译器),不是运行时特性,和垃圾回收有本质的区别 Automatic Refer...

网友评论

    本文标题:编译器特性 _attribute__((packed))

    本文链接:https://www.haomeiwen.com/subject/lhmhzxtx.html