Swift 3 UnsafeMutablePointer initialization for C-type float **

In Swift 3, I need to send data to a C object that accepts the input float ** .

In Swift 2, I used the declaration UnsafeMutablePointer< UnsafeMutablePointer<Float32>> , built a fast array (only for init!) And passed it to the pointer, and it worked:

  var bufferOut: UnsafeMutablePointer< UnsafeMutablePointer<Float32>>? arrayOut = Array(repeating: Array(repeating: 0, count: Int(size1), count: Int(size2)) bufferOut = UnsafeMutablePointer< UnsafeMutablePointer<Float32>>(arrayOut) 

In Swift 3, it's all broken!

  • What is the most Swifty way to pass C-Style float** and initialize it?
  • What would be the best way to assign values ​​to UnsafeMutablePointer< UnsafeMutablePointer<T>> ?

The docs say that for T ** should use AutoreleasingUnsafeMutablePointer<T> , but I never managed to create one!

Please note that I really don't care about the array in the above example! If I could just initialize the pointer directly using the known features, I would do it.

Note : Expected Use Cases The UnsafeRawPointer section describes useful situations, such as C-array and C-buffers, however, translation of such methods for the above construction is not obvious!

0
source share
1 answer

This is what I did and work. It follows the recommendations of the new UnsafeMuTablePointer help showing sample programs on simple diagrams. Thus, it is required to allocate and assign each slot, starting from the top level!

So, in order to build UnsafeMutablePointer< UnsafeMutablePointer<T>> size (size1, size2) (for example, a matrix), you can go as follows using an intermediate vector called vectorBuf :

  var vectorBuf : UnsafeMutablePointer<T>? vectorBuf = UnsafeMutablePointer<T>.allocate(capacity: size2) for index in 0...(size2) { // had Int(channelCount)* vectorBuf!.advanced(by: index).pointee = 0.0 } /// This is where allocation and initialization happens: bufferOut = UnsafeMutablePointer< UnsafeMutablePointer<T>?>.allocate(capacity: Int(size1)) for index in 0...Int(size1) { bufferOut!.advanced(by: index).pointee = UnsafeMutablePointer<T>.allocate(capacity: (size2) ) bufferOut!.advanced(by: index).pointee?.assign(from: vectorBuf!, count: size2) } 

Hope this can be useful for others trying to use swift with signal processing calls in C / C ++!

+2
source

Source: https://habr.com/ru/post/1257986/


All Articles