无法转换类型&#39; UnsafePointer <midinotification>&#39;的值预期参数类型&#39; UnsafePointer&lt; _&gt;&#39;

时间:2018-04-02 11:58:31

标签: swift coremidi unsafe-pointers

我正在尝试更新我在http://mattg411.com/swift-coremidi-callbacks/找到的CoreMidi示例中的代码

代码是Swift 3之前的日期,所以我需要做一些调整。 问题是我基本上不需要玩不安全的指针和朋友。所以我想我已经设法解决了一些问题,但是其中一个问题仍然存在并且给我发现了这个错误Cannot convert value of type 'UnsafePointer<MIDINotification>' to expected argument type 'UnsafePointer<_>'给出此错误的代码是...UnsafePointer<MIDIObjectAddRemoveNotification>(message)

这种方法的一部分:

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

编辑: 我从网上找到的几个教程中创建了一个小项目。 包括来自user28434的修复

https://github.com/nissaba/Librarian

1 个答案:

答案 0 :(得分:0)

如果我正确理解了代码,请

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

应该将记忆从MIDINotification重新绑定到MIDIObjectAddRemoveNotification

在Swift 3.0+中,你应该使用withMemoryRebound(to:capacity:_:)

这样的事情:

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

或者还有另一种方法:将UnsafePointer投射到UnsafeRawPointer然后"assume memory bound"

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