关于Objective C:Swift数组与C的互操作性?

Inter-operability of Swift arrays with C?

如何传递或复制C数组中的数据,例如

1
float foo[1024];

,在使用固定大小数组的C函数和Swift函数之间,例如

声明的

1
let foo = Float[](count: 1024, repeatedValue: 0.0)


我认为这不可能轻易实现。与不能将C样式数组用于使用NSArray的参数的方式相同。

Swift中的所有C数组都用UnsafePointer表示,例如UnsafePointer<Float>。 Swift并不真正知道数据是数组。如果要将它们转换为Swift数组,则将创建一个新对象,然后逐个复制其中的项目。

1
2
3
4
5
6
7
let array: Array<Float> = [10.0, 50.0, 40.0]

// I am not sure if alloc(array.count) or alloc(array.count * sizeof(Float))
var cArray: UnsafePointer<Float> = UnsafePointer<Float>.alloc(array.count)
cArray.initializeFrom(array)

cArray.dealloc(array.count)

编辑

只是找到了一个更好的解决方案,实际上可以避免复制。

1
2
3
4
5
6
let array: Array<Float> = [10.0, 50.0, 40.0]

// .withUnsafePointerToElements in Swift 2.x
array.withUnsafeBufferPointer() { (cArray: UnsafePointer<Float>) -> () in
    // do something with the C array
}


从Beta 5开始,一个人只能使用通行证


n


n