- Size is the number of bytes to read from the pointer to reach all the data.
- Stride is the number of bytes to advance to reach the next item in the buffer.
- Alignment is the the “evenly divisible by” number that each instance needs to be at. If you’re allocating memory to copy data into, you need to specify the correct alignment (e.g.
allocate(byteCount: 100, alignment: 4)
).
这里的instance理解为struct里的 每个member的对齐
MemoryLayout<Int>.size
// returns 8 on my pc
MemoryLayout<Int32>.size
// returns 4
MemoryLayout<Int32>.alignment
// returns 4
MemoryLayout<Int32>.stride
// returns 4
注意bool的对齐
struct CertifiedPuppy1 {
let age: Int
let isTrained: Bool
let isCertified: Bool
}
MemoryLayout<CertifiedPuppy1>.size // 10
MemoryLayout<CertifiedPuppy1>.stride // 16
MemoryLayout<CertifiedPuppy1>.alignment // 8
struct CertifiedPuppy2 {
let isTrained: Bool
let age: Int
let isCertified: Bool
}
MemoryLayout<CertifiedPuppy2>.size // 17
MemoryLayout<CertifiedPuppy2>.stride // 24
MemoryLayout<CertifiedPuppy2>.alignment // 8