如何传递或复制 C 数组中的数据,例如
float foo[1024];
,在使用固定大小数组的 C 和 Swift 函数之间,例如由
声明的let foo = Float[](count: 1024, repeatedValue: 0.0)
?
最佳答案
我不认为这很容易实现。就像您不能将 C 样式数组用于使用 NSArray
的参数一样.
Swift 中的所有 C 数组都由 UnsafePointer
表示,例如UnsafePointer<Float>
. Swift 并不知道数据是一个数组。如果您想将它们转换为 Swift 数组,您需要创建一个新对象并将其中的项目一一复制。
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)
编辑
刚刚找到了一个更好的解决方案,这实际上可以避免复制。
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
}
关于objective-c - Swift 数组与 C 的互操作性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24100553/