Using Swift CFunctionPointer to pass a callback to CoreMIDI API

前端 未结 2 2023
南旧
南旧 2020-11-30 08:51

It may be that this is actually not possible currently, which would be unfortunate. I\'m trying to call the CoreMIDI API to set up a MIDI input. This is what I\'m trying to

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-30 09:32

    Swift 1.x (Old Way)

    There's a way to do that - Objective-C Runtime is the trick.

    import CoreMIDI
    
    let block : @objc_block
    (UnsafePointer,
    UnsafeMutablePointer,
    UnsafeMutablePointer) -> Void =
    { (pktlist,readProcRefCon,srcConnRefCon) in
    
        //Your code goes here...
    }
    
    let imp : COpaquePointer =
        imp_implementationWithBlock(unsafeBitCast(block, AnyObject.self))
    
    let callback : MIDIReadProc = unsafeBitCast(imp, MIDIReadProc.self)
    

    Works with CoreFoundation callbacks. Should work for CoreMIDI too.


    Swift 2.x (New Way)

    In Swift 2 the process becomes "less hacky" (and slightly more readable).

    import CoreMIDI
    
    let callback : @convention(c) (pktlist : UnsafePointer,
                                   readProcRefCon : UnsafeMutablePointer,
                                   srcConnRefCon : UnsafeMutablePointer) -> Void =
    
    { (pktlist, readProcRefCon, srcConRefCon) in
    
    }
    
    let usableCallback = unsafeBitCast(callback, MIDIReadProc.self)
    

提交回复
热议问题