这是一个错误:
'init' is unavailable:use 'withMemoryRebound(to:capacity:_)' to temporarily view memory as another layout-compatible type.
这是我的代码:
var inputSignal:[Float] = Array(repeating: 0.0, count: 512)
let xAsComplex = UnsafePointer<DSPComplex>( inputSignal.withUnsafeBufferPointer { $0.baseAddress } )//error here
为什么呢?如何解决?
答案 0 :(得分:2)
首先,不建议使用成语.withUnsafeBufferPointer { $0.baseAddress }
来获取Swift Array
的地址。从该成语中获取的地址不保证在关闭之外有效。
所以,你可以这样写:
inputSignal.withUnsafeBufferPointer {buffer in
buffer.baseAddress!.withMemoryRebound(to: DSPComplex.self, capacity: inputSignal.count / (MemoryLayout<DSPComplex>.size/MemoryLayout<Float>.size)) {xAsComplex in
//`xAsComlex` is guaranteed to be valid only in this closure.
//...
}
}
如果需要使用稳定指针,则可能需要将它们作为实际指针进行管理。
let inputSignalCount = 512
let inputSignal = UnsafeMutablePointer<Float>.allocate(capacity: inputSignalCount)
inputSignal.initialize(to: 0.0, count: inputSignalCount)
//...
inputSignal.withMemoryRebound(to: DSPComplex.self, capacity: inputSignalCount / (MemoryLayout<DSPComplex>.size/MemoryLayout<Float>.size)) {xAsComplex in
//`xAsComlex` is guaranteed to be valid only in this closure.
//...
}
//...
//Later when `inputSignal` is not needed any more...
inputSignal.deinitialize(count: inputSignalCount)
inputSignal.deallocate(capacity: inputSignalCount)