Objective-C Wrapper for CFunctionPointer to a Swift Closure

后端 未结 2 1693
失恋的感觉
失恋的感觉 2020-12-03 15:53

I am playing with Swift and noticed that Swift does not allow to create CFFunctionPointers. It can only pass around and reference existing ones.

As for example Core

2条回答
  •  时光说笑
    2020-12-03 16:10

    I needed to define this callback:

    typedef void (*MIDIReadProc) ( const MIDIPacketList *pktlist, void *readProcRefCon, void *srcConnRefCon );
    

    and I wanted to use Objective-C as least as possible.

    This was my approach:

    MIDIReadProcCallback.h

    #import 
    #import 
    
    typedef void (^OnCallback)(const MIDIPacketList *packetList);
    
    @interface MIDIReadProcCallback : NSObject
    
    + (void (*)(const MIDIPacketList *pktlist, void *readProcRefCon, void *srcConnRefCon))midiReadProc;
    + (void)setOnCallback:(OnCallback)onCallback;
    
    @end
    

    MIDIReadProcCallback.m

    #import "MIDIReadProcCallback.h"
    
    static OnCallback _onCallback = nil;
    
    static void readProcCallback(const MIDIPacketList *pktlist, void *refCon, void *connRefCon) {
        if (_onCallback) {
            _onCallback(pktlist);
        }
    }
    
    @implementation MIDIReadProcCallback
    
    + (void (*)(const MIDIPacketList *pktlist, void *readProcRefCon, void *srcConnRefCon))midiReadProc {
        return readProcCallback;
    }
    
    + (void)setOnCallback:(OnCallback)onCallback {
        _onCallback = onCallback;
    }
    
    @end
    

    Then you can register MIDIReadProcCallback.midiReadProc as callback and set handler MIDIReadProcCallback.setOnCallback({ (packetList: MIDIPacketList) in ... })

提交回复
热议问题