Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 738
JackPearse Avatar asked Dec 12 '25 11:12

JackPearse


1 Answers

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

like image 182
Kirsteins Avatar answered Dec 14 '25 01:12

Kirsteins



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!