Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

swift3

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?

like image 647
J.doouuu Avatar asked Oct 29 '22 20:10

J.doouuu


1 Answers

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)
like image 114
OOPer Avatar answered Nov 03 '22 14:11

OOPer