AhmedZah
AhmedZah

Reputation: 1203

Swift 3 migration : Cannot convert value of type [UnsafeMutablePointer<Int32>] to expected argument type UnsafeMutablePointer<Int32>?

I have a little Problem with my Code after updating to Swift 3. I had this Code before the conversion:

            var leftChannel = [Int32]()
            var rightChannel = [Int32]()

            for index in 0...(samples.count - 1) {
                leftChannel.append(Int32(samples[index]) * 256)
                rightChannel.append(Int32(samples[index]) * 256)
            }

            var pIn:[UnsafeMutablePointer<Int32>] = []

            pIn.append(&leftChannel)
            pIn.append(&rightChannel)


            //PROCESS

            ProcessFunc(&pIn)

ProcessFunc is a C function:

ProcessFunc(smplType **pIn)

And I converted it to this Code and in the ProcessFunc line I get an Error

.... Cannot convert value of type '[UnsafeMutablePointer]' to expected argument type 'UnsafeMutablePointer?'

Does anyone know how to get rid of this?

Upvotes: 1

Views: 2936

Answers (1)

OOPer
OOPer

Reputation: 47876

First of all, you should better check how your ProcessFunc is imported into Swift.

If you write something like this in SomeHeader.h:

typedef int smplType;
extern int ProcessFunc(smplType **pIn);

You can find these in the Generated Interface:

public typealias smplType = Int32
public func ProcessFunc(_ pIn: UnsafeMutablePointer<UnsafeMutablePointer<smplType>?>!) -> Int32

I assume the parameter type of ProcessFunc is as above -- UnsafeMutablePointer<UnsafeMutablePointer<smplType>?>!. (And smplType is Int32.)

Generally, when you want to pass an array of values through UnsafeMutablePointer<T>, you usually declare a variable of Array<T> and pass it as an inout parameter (prefix &).

In your case T is UnsafeMutablePointer<smplType>?, so you need to declare a variable of Array<UnsafeMutablePointer<smplType>?>.

So, your pIn should be like this:

var pIn:[UnsafeMutablePointer<Int32>?] = []

Or, if you want to work with Swift Arrays and pointers in a safer manner, you might need to write something like this:

leftChannel.withUnsafeMutableBufferPointer { leftBP in
    rightChannel.withUnsafeMutableBufferPointer { rightBP in
        var pIn: [UnsafeMutablePointer<Int32>?] = [
            leftBP.baseAddress,
            rightBP.baseAddress
        ]
        //PROCESS

        ProcessFunc(&pIn)
    }
}

But, practically (don't take this as a good meaning), this may not be needed and depends on how your ProcessFunc works.

Upvotes: 1

Related Questions