简体   繁体   中英

Using MemoryLayout on a struct gives the incorrect size

Memory layout behaves a little strange when trying to find the size of a struct.

I can just maintain a function that adds the size of each. But I was wondering if there was a better way.

enum Mode: UInt8 {
    case tings
}

// this should be 5 - UInt8 + UInt16 + UInt16
struct Stuff {
    let mode: Mode
    let sessionID: UInt16
    let sessionCount: UInt16
}
print(MemoryLayout<Stuff>.size)                 // 4 ???
print(MemoryLayout<UInt16>.size)                // 2
print(MemoryLayout<Mode>.size)                  // 0 !?!?!?!?
print(MemoryLayout<Mode.RawValue>.size)         // 1

You cannot rely on simply adding together the sizes of the individual fields of a structure to get the struct's size.

Swift can add padding into the fields of a struct to align fields on various byte boundaries to improve the efficiency in accessing the data at runtime.

If you want to allocate one item, you can simply use the size of the memory layout. If you want a contiguous block of n instances then you should allocate blocks based on the stride of the layout.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM