如何将数组UnsafePointer <dspcomplex>转换为Floats数组?

时间:2019-02-11 21:11:06

标签: ios arrays iphone cocoa

如何在Swift中将数组UnsafePointer<DSPComplex>转换为Floats数组?

我见过this page,但是由于我是新手,所以我不知道如何对一组浮点数进行操作。

1 个答案:

答案 0 :(得分:2)

DSPComplex是一个包含虚数和实数Float值的结构。那是两个花车。无法将其转换为Floats数组。但是,必须先将其转换为UnsafeBufferPointer,然后才能将其传递给Array。然后便有了一个Swift数组的DSPComplex结构。

func arrayForDSPComplex(pointer: UnsafePointer<DSPComplex>, count: Int) -> [DSPComplex] {
   let buffer = UnsafeBufferPointer<DSPComplex>(start: pointer, count: count)
   return Array(buffer)
}

如果需要,甚至可以使用泛型对其进行概括。

func arrayForPointer<T>(_ pointer: UnsafePointer<T>, count: Int) -> [T] {
    let buffer = UnsafeBufferPointer(start: pointer, count: count)
    return Array(buffer)
}

对于可变指针,您需要另一个函数。

func mutableArrayForPointer<T>(_ pointer: UnsafeMutablePointer<T>, count: Int) -> [T] {
    let buffer = UnsafeMutableBufferPointer(start: pointer, count: count)
    return Array(buffer)
}

可以通过将扩展功能放在指针类型上来对其进行一些改进。

extension UnsafePointer {
    func arrayCopying(elementCount: Int) -> [Pointee] {
        let buffer = UnsafeBufferPointer(start: self, count: elementCount)
        return Array(buffer)
    }
}

extension UnsafeMutablePointer {
    func arrayCopying(elementCount: Int) -> [Pointee] {
        let buffer = UnsafeMutableBufferPointer(start: self, count: elementCount)
        return Array(buffer)
    }
}
``