2

How do I convert an array UnsafePointer<DSPComplex> to an array of Floats in Swift?

I have seen this page, but because I am new to swift I don't have a clue on how to do it for an array of floats.

Duck
  • 34,902
  • 47
  • 248
  • 470

1 Answers1

2

The DSPComplex is a structure containing an imaginary and real Float value. That's two floats. It cannot be converted to an array of Floats. However you must convert it to an UnsafeBufferPointer first and then you can pass it to an Array. Then you have a Swift array of DSPComplex structures.

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

You can even generalize it using generics if you want.

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

For mutable pointers you need another function.

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

You can improve it a little bit, by putting the functions as extensions on the pointer types.

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)
    }
}
``
TimTwoToes
  • 695
  • 5
  • 10
  • Xcode complains about the second line with `Cannot invoke initializer for type 'UnsafePointer' with no arguments` – Duck Feb 11 '19 at 23:50
  • Changed the example to be a function – TimTwoToes Feb 11 '19 at 23:58
  • When I pass the result of the second function to a function with this header `func imprimir(_ valores:[Float] = []) ` it complains `Cannot convert value of type '[DSPSplitComplex]' to expected argument type '[Float]'` ... the output of your function is apparently still a DSPSplitComplex – Duck Feb 12 '19 at 00:12
  • That's because the function doesn't produce an array of Floats. You are working with structures, not primitive datatypes that the imprimir function expects. – TimTwoToes Feb 12 '19 at 00:16
  • so, suppose i want just the real part of that complex structure and put that inside an array? – Duck Feb 12 '19 at 00:22
  • Well you are passing in the type `UnsafePointer` that produces a Swift array of the type `[DSPSplitComplex]`. – TimTwoToes Feb 12 '19 at 00:23