Category

Swift and C API callbacks

Swift Language

Swift and C API callbacks

Swift is supposed to have been designed for compatibility with existing Apple APIs, including C APIs such as CoreMIDI.

N.B.

Apple has improved Core MIDI support for Swift since this was written.

Introduction

Core MIDI is Apple’s C API for (surprise) MIDI. Apple provides no higher level bindings besides a player in AVFoundation. If you want to develop an app with MIDI capabilities, you need to use Core MIDI.

Like many C APIs, there are several callbacks:

  • MIDICompletionProc
  • MIDINotifyProc
  • MIDIReadProc

In context, the very first thing you’d do is to create a MIDI client. In Swift 1.2 beta, MIDIClientCreate finally works.! See my posts on the problem and the solution.

One of the parameters to MIDIClientCreate is a function pointer (MIDINotifyProc) to be called when MIDI inputs or outputs in the system have changed, such as plugging in a new device.

Another place where callbacks are used is reading MIDI input. A MIDIReadProc is called when data appears.

Table of Contents

Creating Function Pointers

Ok, so how do you make a CFunctionPointer?
Here is my attempt.
It looks like CFunctionPointer needs a COpaquePointer which needs an UnsafeMutablePointer or UnsafePointer.

BTW., the CFunctionPointer source code has this amusing comment:

CFunctionPointer is a struct with inits that will take an UnsafeMutablePointer or an UnsafePointer.

So, it looks like we need to make an unsafe pointer, use that to create an opaque pointer, then use that to create a function pointer (and a partridge in a pear tree).

Will this work with a MIDIReadProc?

It doesn’t work though with Core MIDI.
And it doesn’t matter if MyMIDIReadProc is a func, a class func, or a global func.

Here is the love letter from Core MIDI:

Swift 2 update

Table of Contents

They heard us. Swift 2 beta has introduced changes in CoreMIDI and function pointers in general.

Here are the new CoreMIDI callback signatures.

  • MIDICompletionProc
  • MIDINotifyProc
  • MIDIReadProc

Table of Contents

Summary

Swift support for C APIs is improving. Given this problem with function pointers though, it is far from being usable.

Resources

3 thoughts on “Swift and C API callbacks”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.