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

1
  • Can you edit question to show the mData declaration? Commented Nov 15, 2016 at 9:33

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.