加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在Swift中对齐vs步幅

发布时间:2020-12-14 05:45:07 所属栏目:百科 来源:网络整理
导读:在Swift 4中,MemoryLayout结构告诉您类型的大小,跨度和对齐方式. 我理解大小和步幅,但不是真正的对齐. 是否有一个示例显示了什么是对齐,它与步幅有什么不同,何时它与步幅有不同的值,以及使用步幅但使用对齐是否正确? 我可以一直计算另一个吗? 这是一个简单
在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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读