Swift: How to use sizeof?

后端 未结 5 1630
逝去的感伤
逝去的感伤 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 18:54

    In Xcode 8 with Swift 3 beta 6 there is no function sizeof (). But if you want, you can define one for your needs. This new sizeof function works as expected with an array. This was not possible with the old builtin sizeof function.

    let bb: UInt8 = 1
    let dd: Double = 1.23456
    
    func sizeof  (_ : T.Type) -> Int
    {
        return (MemoryLayout.size)
    }
    
    func sizeof  (_ : T) -> Int
    {
        return (MemoryLayout.size)
    }
    
    func sizeof  (_ value : [T]) -> Int
    {
        return (MemoryLayout.size * value.count)
    }
    
    sizeof(UInt8.self)   // 1
    sizeof(Bool.self)    // 1
    sizeof(Double.self)  // 8
    sizeof(dd)           // 8
    sizeof(bb)           // 1
    
    var testArray: [Int32] = [1,2,3,4]
    var arrayLength = sizeof(testArray)  // 16
    

    You need all versions of the sizeof function, to get the size of a variable and to get the correct size of a data-type and of an array.

    If you only define the second function, then sizeof(UInt8.self) and sizeof(Bool.self) will result in "8". If you only define the first two functions, then sizeof(testArray) will result in "8".

提交回复
热议问题