'init' is not available: use 'fromMemoryRebound (to: capacity: _)' to temporarily view memory as another type of mock compatible

here is the error:

'init' is unavailable:use 'withMemoryRebound(to:capacity:_)' to temporarily view memory as another layout-compatible type. 

here is my code:

 var inputSignal:[Float] = Array(repeating: 0.0, count: 512) let xAsComplex = UnsafePointer<DSPComplex>( inputSignal.withUnsafeBufferPointer { $0.baseAddress } )//error here 

why? How to fix it?

+5
source share
1 answer

First of all, using idiom .withUnsafeBufferPointer { $0.baseAddress } to accept a Swift Array address is not recommended. An address taken from this idiom is not guaranteed to be valid outside of closure.

So you can write something like this:

 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. //... } } 

If you need to use stable pointers, you may need to manage them as actual pointers.

 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) 
+2
source

All Articles