ios - 如何将数组 `UnsafePointer<DSPComplex>` 转换为 float 组?
<p><p>如何在 Swift 中将数组 <code>UnsafePointer<DSPComplex></code> 转换为 Floats 数组?</p>
<p>我见过<a href="https://stackoverflow.com/questions/32606989/converting-an-unsafepointer-with-length-to-a-swift-array-type" rel="noreferrer noopener nofollow">this page</a> ,但是因为我是 swift 新手,所以我不知道如何处理一组 float 。</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>DSPComplex 是一个包含虚数和实数浮点值的结构。那是两个花车。它不能转换为 float 组。但是,您必须先将其转换为 UnsafeBufferPointer,然后才能将其传递给数组。然后你就有了一个 Swift 的 DSPComplex 结构数组。</p>
<pre><code>func arrayForDSPComplex(pointer: UnsafePointer<DSPComplex>, count: Int) -> {
let buffer = UnsafeBufferPointer<DSPComplex>(start: pointer, count: count)
return Array(buffer)
}
</code></pre>
<p>如果需要,您甚至可以使用泛型对其进行概括。</p>
<pre><code>func arrayForPointer<T>(_ pointer: UnsafePointer<T>, count: Int) -> {
let buffer = UnsafeBufferPointer(start: pointer, count: count)
return Array(buffer)
}
</code></pre>
<p>对于可变指针,您需要另一个函数。</p>
<pre><code>func mutableArrayForPointer<T>(_ pointer: UnsafeMutablePointer<T>, count: Int) -> {
let buffer = UnsafeMutableBufferPointer(start: pointer, count: count)
return Array(buffer)
}
</code></pre>
<p>您可以通过将函数作为指针类型的扩展来稍微改进它。</p>
<pre><code>extension UnsafePointer {
func arrayCopying(elementCount: Int) -> {
let buffer = UnsafeBufferPointer(start: self, count: elementCount)
return Array(buffer)
}
}
extension UnsafeMutablePointer {
func arrayCopying(elementCount: Int) -> {
let buffer = UnsafeMutableBufferPointer(start: self, count: elementCount)
return Array(buffer)
}
}
``
</code></pre></p>
<p style="font-size: 20px;">关于ios - 如何将数组`UnsafePointer<DSPComplex>` 转换为 float 组?,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/54639225/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/54639225/
</a>
</p>
页:
[1]