Inter-operability of Swift arrays with C?
如何传递或复制C数组中的数据,例如
1 | float foo[1024]; |
,在使用固定大小数组的C函数和Swift函数之间,例如
声明的
1 | let foo = Float[](count: 1024, repeatedValue: 0.0) |
?
我认为这不可能轻易实现。与不能将C样式数组用于使用
Swift中的所有C数组都用
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