gpt4 book ai didi

ios - 'init' 不可用 :use 'withMemoryRebound(to:capacity:_)' to temporarily view memory as another layout-compatible type

转载 作者:可可西里 更新时间:2023-11-01 04:45:09 24 4
gpt4 key购买 nike

这是一个错误:

'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

为什么?如何解决?

最佳答案

首先,不推荐使用成语.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)

关于ios - 'init' 不可用 :use 'withMemoryRebound(to:capacity:_)' to temporarily view memory as another layout-compatible type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39567692/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com