5

here is an 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?

J.doouuu
  • 65
  • 5

1 Answers1

2

First of all, using the idiom .withUnsafeBufferPointer { $0.baseAddress } to take an address of Swift Array is not recommended. The address taken from that idiom is not guaranteed to be valid outside the 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)
OOPer
  • 44,179
  • 5
  • 90
  • 123