Nouman
Nouman

Reputation: 410

Swift casting UnsafeMutablePointer<Void> in C callback

Trying to interface with iOS AudioQueues using swift, and hitting a roadblock when attempting to pass an object defining my state.

My state object is a custom struct defined as:

struct UserData {
var active: Bool = false
var audioFileId: AudioFileID = nil
}

My swift audio input callback:

        let myCallback : @convention(c) (UnsafeMutablePointer<Void>, AudioQueueRef, AudioQueueBufferRef, UnsafePointer<AudioTimeStamp>, UInt32, UnsafePointer<AudioStreamPacketDescription>) -> Void = {
        (inUserData, inAQ, inBuffer, inStartTime, inNumberPacketDescriptions, inPacketDescs) -> Void in
      ...
    }

Lastly, initializing the audio queue:

        AudioQueueNewInput(&audioStreamBasicDescription, myCallback, &userData, nil, nil, 0, &inputQueue)

Where I'm stuck is figuring out how to cast inUserData: UnsafeMutablePointer<Void> to my UserData struct

Or, of course, any better way of handling this.

Thanks!

Upvotes: 2

Views: 606

Answers (1)

eik
eik

Reputation: 4600

You can use either

let userData: UserData = UnsafePointer(inUserData).memory

or

let userData = UnsafePointer<UserData>(inUserData).memory

both are equivalent. See also the UnsafeMutablePointer Structure Reference.

To return some modified data you can use

let userDataReference = UnsafeMutablePointer<UserData>(inUserData)
var userData = userDataReference.memory
userData.… = … /* modifiy local copy */
userDataReference.memory = userData

You could also modify userDataReference.memory directly, but I would advise against it.

Upvotes: 2

Related Questions