swiftcoremidiunsafe-pointers

Cannot convert value of type 'UnsafePointer<MIDINotification>' to expected argument type 'UnsafePointer<_>'


I am trying to update the code from a CoreMidi exemple I found at http://mattg411.com/swift-coremidi-callbacks/

And the code is date to before Swift 3, so I need to make some ajustement. Problem is I have basically never needed to play with unsafe pointers and friends. So I think I have managed to solve a few of the problems, but one them remainsand get me this error Cannot convert value of type 'UnsafePointer<MIDINotification>' to expected argument type 'UnsafePointer<_>' the code that give this error is ...UnsafePointer<MIDIObjectAddRemoveNotification>(message)

part of this methode:

func MIDIUtil_MIDINotifyProc(message: UnsafePointer<MIDINotification>, refCon: UnsafeMutableRawPointer) -> Void
    {
        let notification:MIDINotification = message.pointee

        if (notification.messageID == .msgObjectAdded || notification.messageID == .msgObjectRemoved)
        {
            let msgPtr:UnsafePointer<MIDIObjectAddRemoveNotification> = UnsafePointer<MIDIObjectAddRemoveNotification>(message)
            let changeMsg:MIDIObjectAddRemoveNotification = msgPtr.pointee
            let h:AnyObject = unbridgeMutable(ptr: refCon)
            let handler:MIDICallbackHandler = h as! MIDICallbackHandler
            handler.processMidiObjectChange(message: changeMsg)
        }
    }

EDIT: I have created a small project from the few tutorials I found on the net. including the fix from user28434

https://github.com/nissaba/Librarian


Solution

  • If I understood code correctly, line

    let msgPtr:UnsafePointer<MIDIObjectAddRemoveNotification> = UnsafePointer<MIDIObjectAddRemoveNotification>(message)
    

    should rebind memory from MIDINotification to MIDIObjectAddRemoveNotification.

    In Swift 3.0+ you should do it using withMemoryRebound(to:capacity:_:).

    Something like this:

    let msgPtr:UnsafePointer<MIDIObjectAddRemoveNotification> = message.withMemoryRebound(to: MIDIObjectAddRemoveNotification.self, capacity: 1) { (pointer) in
        return pointer
    }
    

    Or there's another way: By casting UnsafePointer to UnsafeRawPointer and then "assume memory bound":

    let msgPtr:UnsafePointer<MIDIObjectAddRemoveNotification> = UnsafeRawPointer(message).assumingMemoryBound(to: MIDIObjectAddRemoveNotification.self)