0

我的鳕鱼长这样

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 有原始数据。我该如何解决这个问题。提前致谢

4

2 回答 2

1

假设它buffer来自AudioBuffer框架AVFoundationbuffer.mData是一个“可选原始指针” UnsafeMutableRawPointer?,并且在 Swift 3 中,您必须将原始指针绑定 到类型化指针:

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

于 2016-11-15T10:10:30.623 回答
0

根据文档:

// 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)

有不同的方法可以转换UnsafeMutableRawPointerUnsafeMutablePointer<T>. Martin 在上面的答案中已经给出了一个转换,另一个在这个例子中。

于 2016-11-15T12:11:50.263 回答