我有一个来自C库的ptr,它指向一个Floats数组。它的类型是UnsafeMutablePointer。如何在Swift 3中创建一个本机[Float]数组?
这是我尝试的内容:
var reconstructedFloats = [Float](repeatElement(0, count: size))
reconstructedFloats.withUnsafeMutableBufferPointer {
let reconstructedFloatsPtr = $0
print(type(of:$0)) // "UnsafeMutableBufferPointer<Float>"
cFloatArrayPtr?.withMemoryRebound(to: [Float].self, capacity: size) {
UnsafeMutableRawPointer(reconstructedFloatsPtr.baseAddress!).storeBytes(of: $0.pointee, as: Float.self)
}
UnsafeMutableRawPointer(reconstructedFloatsPtr.baseAddress!).storeBytes(of: (cFloatArrayPtr?.pointee)!, as: Float.self)
}
这似乎过于复杂,所以希望这是一种简单的方法,但即使这段代码也会产生编译错误:Type of expression is ambiguous without more context
。
如果你想将它插入游乐场,这里有一个设计cFloatArrayPtr的完整样本:
// Let's contrive a C array ptr:
var size = 3
var someFloats: [Float] = [0.1, 0.2, 0.3]
var cFloatArrayPtr: UnsafeMutablePointer<Float>?
someFloats.withUnsafeMutableBufferPointer {
cFloatArrayPtr = $0.baseAddress
}
print(type(of:cFloatArrayPtr!)) // "UnsafeMutablePointer<Float>"
var reconstructedFloats = [Float](repeatElement(0, count: size))
reconstructedFloats.withUnsafeMutableBufferPointer {
let reconstructedFloatsPtr = $0
print(type(of:$0))
cFloatArrayPtr?.withMemoryRebound(to: [Float].self, capacity: size) {
UnsafeMutableRawPointer(reconstructedFloatsPtr.baseAddress!).storeBytes(of: $0.pointee, as: Float.self)
}
UnsafeMutableRawPointer(reconstructedFloatsPtr.baseAddress!).storeBytes(of: (cFloatArrayPtr?.pointee)!, as: Float.self)
}
print(reconstructedFloats)
答案 0 :(得分:5)
您可以从指针中制作UnsafeBufferPointer
。 UnsafeBufferPointer
是Sequence
,因此您可以直接从中创建数组:
let buffer = UnsafeBufferPointer(start: cFloatArrayPtr, count: size)
var reconstructedFloats = Array(buffer)
当然,这会创建一个副本。