Inter-operability of Swift arrays with C?

前端 未结 4 1926
终归单人心
终归单人心 2021-02-02 09:46

How can one pass or copy the data in a C array, such as

float foo[1024];

, between C and Swift functions that use fixed size arrays, such as d

4条回答
  •  不思量自难忘°
    2021-02-02 10:24

    I don't think this is easily possible. In the same way as you can't use C style arrays for parameters working with a NSArray.

    All C arrays in Swift are represented by an UnsafePointer, e.g. UnsafePointer. Swift doesn't really know that the data are an array. If you want to convert them into a Swift array, you will have create a new object and copy the items there one by one.

    let array: Array = [10.0, 50.0, 40.0]
    
    // I am not sure if alloc(array.count) or alloc(array.count * sizeof(Float))
    var cArray: UnsafePointer = UnsafePointer.alloc(array.count)
    cArray.initializeFrom(array)
    
    cArray.dealloc(array.count)
    

    Edit

    Just found a better solution, this could actually avoid copying.

    let array: Array = [10.0, 50.0, 40.0]
    
    // .withUnsafePointerToElements in Swift 2.x
    array.withUnsafeBufferPointer() { (cArray: UnsafePointer) -> () in
        // do something with the C array
    }
    

提交回复
热议问题