Swift 3迁移:无法将[UnsafeMutablePointer <int32>]类型的值转换为预期的参数类型UnsafeMutablePointer <int32>?

时间:2017-02-22 14:31:04

标签: swift3 unsafemutablepointer

更新到Swift 3后,我的代码有点问题。转换前我有这个代码:

            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是一个C函数:

ProcessFunc(smplType **pIn)

我将它转换为此代码,并在ProcessFunc行中出现错误

  

....无法将'[UnsafeMutablePointer]'类型的值转换为预期的参数类型'UnsafeMutablePointer?'

有谁知道怎么摆脱这个?

1 个答案:

答案 0 :(得分:1)

首先,您应该更好地检查ProcessFunc如何导入Swift。

如果你在SomeHeader.h中写这样的东西:

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

您可以在Generated Interface中找到这些:

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

我假设参数类型ProcessFunc如上所述 - UnsafeMutablePointer<UnsafeMutablePointer<smplType>?>!。 (而smplTypeInt32。)

通常,当您想要通过UnsafeMutablePointer<T>传递值数组时,通常会声明一个Array<T>变量并将其作为inout参数(前缀&)传递。

在您的情况下,TUnsafeMutablePointer<smplType>?,因此您需要声明Array<UnsafeMutablePointer<smplType>?>的变量。

所以,你的pIn应该是这样的:

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

或者,如果你想以更安全的方式使用Swift Arrays和指针,你可能需要写这样的东西:

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

        ProcessFunc(&pIn)
    }
}

但是,实际上(不要认为这是一个好的意思),这可能不需要,取决于你的ProcessFunc如何运作。