iosarraysobjective-cswiftunsafemutablepointer

Turn an array of array of float numbers into UnsafeMutablePointer<UnsafeMutablePointer<Float>>


I need to use a function that uses UnsafeMutablePointer<UnsafeMutablePointer<Float>?>! as a parameter. It's written in a framework in Objective-C++ and I'm accessing it through a bridging header:

- (void) applyFilters: (float *) input_image input_params: (long *) input_params output_image : (float *) output_image output_params : (long *) output_params filter_id : (int) filter_id args : (float**) args

I'm having some trouble understanding the structure of the args parameter, which is float**. In Swift, it asks for a parameter of type UnsafeMutablePointer<UnsafeMutablePointer<Float>>, which I'm guessing points to an array of array of floats.

applyFilters(input_image: UnsafeMutablePointer<Float>!UnsafeMutablePointer<Float>!, input_params: UnsafeMutablePointer<Int>!, output_image: UnsafeMutablePointer<Float>!, output_params: UnsafeMutablePointer<Int>!, filter_id: Int32, args: UnsafeMutablePointer<UnsafeMutablePointer<Float>?>!)

If I create an array of array of floats, how do I point to it using UnsafeMutablePointer<UnsafeMutablePointer<Float>> so I can pass it to a C++ function?


Solution

  • Figured out how to do it:

    func arrayOfArrayExample() {
    
        let floatArray: [[Float]] = [
            [50.0, 23.0, 15.6],
            [24.0, 9.5, 12.7]
        ]
    
        let size1 = floatArray.count
        let size2 = floatArray[0].count
    
        var vectorBuf : UnsafeMutablePointer<Float>?
        let bufferOut = UnsafeMutablePointer< UnsafeMutablePointer<Float>?>.allocate(capacity: Int(size1))
    
        for i in 0..<size1 {
            vectorBuf = UnsafeMutablePointer<Float>.allocate(capacity: size2)
            for j in 0..<size2 {
                vectorBuf!.advanced(by: j).pointee = floatArray[i][j]
            }
            bufferOut.advanced(by: i).pointee = vectorBuf
        }
    
        defer {
            //deallocating memory
            for i in 0..<size1 {
                bufferOut.advanced(by: i).deallocate()
            }
        }
    }
    

    The variable bufferOut returns an UnsafeMutablePointer<UnsafeMutablePointer<Float>> pointer that points to an array of array of Float, deallocating memory afterwards.