在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.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。