swift3 中的 UnsafeMutablePointer 错误

Error in UnsafeMutablePointer in swift3

我的鳕鱼是这样的

let samples = UnsafeMutableBufferPointer<Int16>(start:UnsafeMutablePointer(buffer.mData), count: Int(buffer.mDataByteSize)/sizeof(Int16))

虽然 运行 此代码生成以下错误

Cannot invoke initializer for type 'UnsafeMutablePointer<_>' with an argument list of type '(UnsafeMutableRawPointer?)'

buffer.mdata 有原始数据。我该如何解决这个问题。提前致谢

假设 buffer 是来自 AVFoundationAudioBuffer 框架:buffer.mData 是一个 "optional raw pointer" UnsafeMutableRawPointer?,在 Swift 3 中你必须 bind 指向类型化指针的原始指针:

let buffer: AudioBuffer = ...

if let mData = buffer.mData {
    let numSamples = Int(buffer.mDataByteSize)/MemoryLayout<Int16>.size
    let samples = UnsafeMutableBufferPointer(start: mData.bindMemory(to: Int16.self, capacity: numSamples),
                                             count: numSamples)
    // ...
}

SE-0107 UnsafeRawPointer API 有关原始指针的更多信息。

根据文档:

// Creates an UnsafeMutablePointer over the count contiguous Element instances beginning at start.
init(start: UnsafeMutablePointer<Element>?, count: Int)

所以

let samples = UnsafeMutableBufferPointer<Int16>(start:UnsafeMutablePointer(buffer.mData), count: Int(buffer.mDataByteSize)/sizeof(Int16))

会像:

let byteSize = Int16(buffer.mDataByteSize)/sizeOf(Int16)
let buffer:UnsafeMutablePointer<Int16> = buffer.mData.assumingMemoryBound(to: Int16.self)
let samples = UnsafeMutableBufferPointer<Int16>(start:buffer, count:byteSize)

有多种方法可以将 UnsafeMutableRawPointer 转换为 UnsafeMutablePointer<T>。 Martin 在上面的回答中已经给出了一种转换,另一种转换在这个例子中。