0

My codd look like this

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

While running this code is generating the following error

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

buffer.mdata is having raw data. How can I solve this issue. Thanks in advance

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
Sachin
  • 135
  • 9

2 Answers2

1

Assuming that buffer is a AudioBuffer from the AVFoundation framework: buffer.mData is a "optional raw pointer" UnsafeMutableRawPointer?, and in Swift 3 you have to bind the raw pointer to a typed pointer:

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

See SE-0107 UnsafeRawPointer API for more information about raw pointers.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
0

As per the documentation:

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

So

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

will be like:

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)

There are different ways to convert UnsafeMutableRawPointer to UnsafeMutablePointer<T>. One conversion is already given by Martin in above answer, and other is in this example.

Ankit Thakur
  • 4,739
  • 1
  • 19
  • 35