Swift: How to use sizeof?

后端 未结 5 1631
逝去的感伤
逝去的感伤 2020-11-29 18:34

In order to integrate with C API\'s while using Swift, I need to use the sizeof function. In C, this was easy. In Swift, I am in a labyrinth of type errors.

I have

5条回答
  •  天命终不由人
    2020-11-29 19:08

    Updated for Swift 3

    Be careful that MemoryLayout.size means something different than sizeof in C/Obj-C. You can read this old thread https://devforums.apple.com/message/1086617#1086617

    Swift uses an generic type to make it explicit that the number is known at compile time.

    To summarize, MemoryLayout.size is the space required for a single instance while MemoryLayout.stride is the distance between successive elements in a contiguous array. MemoryLayout.stride in Swift is the same as sizeof(type) in C/Obj-C.

    To give a more concrete example:

    struct Foo {
      let x: Int
      let y: Bool
    }
    
    MemoryLayout.size      // returns 8 on 64-bit
    MemoryLayout.size     // returns 1
    MemoryLayout.size      // returns 9
    MemoryLayout.stride    // returns 16 because of alignment requirements
    MemoryLayout.alignment // returns 8, addresses must be multiples of 8
    

提交回复
热议问题