JackPearse
JackPearse

Reputation: 2942

How to implement C-Style callback functions using swift?

I found an example for IOKit:

var notification:io_object_t

let matching:NSDictionary = IOServiceNameMatching("IODisplayWrangler").takeRetainedValue()
let displayWrangler = IOServiceGetMatchingService(kIOMasterPortDefault, matching)
let notificationPort = IONotificationPortCreate(kIOMasterPortDefault)
    IOServiceAddInterestNotification(notificationPort, displayWrangler, kIOGeneralInterest, displayPowerNotificationsCallback, nil, &notification)

CFRunLoopAddSource (CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(notificationPort), kCFRunLoopDefaultMode);
   IOObjectRelease (displayWrangler);

The above example is clear to me - so far. But IOServiceAddInteresNotification wants a callback function. In it's simple to do this, by implementing the C-Style function somewhere in the .m-file.

The documentation says that I have to use a callback of type IOServiceInterestCallback.

In C-Style it is defined as follows:

typedef void ( *IOServiceInterestCallback)( void *refcon, io_service_t service, uint32_t messageType, void *messageArgument );

And on objC everything seems to work out perfectly. What is the equivalent solution in swift? How do I declare the callback function without creating a C or objC file for this?

Any ideas?

Cheers,

Jack

Upvotes: 3

Views: 1424

Answers (1)

Kirsteins
Kirsteins

Reputation: 27335

You cannot create C function like callbacks in Swift as closures are not compatible with CFunctionPointer. You can implement some workaround in Objective-C or C. Example is describe in Objective-C Wrapper for CFunctionPointer to a Swift Closure

Upvotes: 2

Related Questions