在Swift中对齐vs步幅

在Swift 4中,MemoryLayout结构告诉您类型的大小,跨度和对齐方式.

我理解大小和步幅,但不是真正的对齐.

是否有一个示例显示了什么是对齐,它与步幅有什么不同,何时它与步幅有不同的值,以及使用步幅但使用对齐是否正确?

我可以一直计算另一个吗?

这是一个简单的例子:
struct Foo {
    let a: Int16
    let b: Int8
}

print(MemoryLayout<Foo>.size)       // 3
print(MemoryLayout<Foo>.alignment)  // 2
print(MemoryLayout<Foo>.stride)     // 4

>结构的对齐是所有结构的最大对齐
字段,在这种情况下最大为2和1.
>结构的步幅是四舍五入到对齐,
这里3舍入到4的倍数.

步幅是内存中相同类型的连续实例(开始)之间的距离:

let array = [Foo(a: 1,b:2),Foo(a: 3,b: 4),Foo(a: 5,b: 6)]
array.withUnsafeBytes {
    print(Data($0) as NSData) // <01000234 03000474 0500066f>
    print($0.count) // 12
}

struct stride是struct alignment的倍数,因此
所有实例(以及所有实例字段)都已正确对齐.

细节可以在
Type Layout

Fragile Struct and Tuple Layout

Structs and tuples currently share the same layout algorithm,noted as the “Universal” layout algorithm in the compiler implementation. The algorithm is as follows:

  • Start with a size of 0 and an alignment of 1.
  • Iterate through the
    fields,in element order for tuples,or in var declaration order for
    structs. For each field:
    • Update size by rounding up to the alignment
      of the field,that is,increasing it to the least value greater or
      equal to size and evenly divisible by the alignment of the field.
    • Assign the offset of the field to the current value of size.
    • Update
      size by adding the size of the field.
    • Update alignment to the max of
      alignment and the alignment of the field.
  • The final size and alignment are the size and alignment of the aggregate. The stride of the type is the final size rounded up to alignment.

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...