3

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

Chris
  • 7,270
  • 19
  • 66
  • 110
JackPearse
  • 2,922
  • 23
  • 31
  • objective-c and swift's function and block (closure) types can generally be used interchangeably. have you tried writing a swift function that matches the required signature and using that? – Patrick Goley Jan 16 '15 at 15:42
  • Yes, I already tried this idea. But swift complained about the void* and uint32_t (which don't exist) why I didn't manage to implement it. – JackPearse Jan 16 '15 at 15:43
  • IOServiceInterestCallback is defined in swift. Do you know the syntax how to use a predefined function prototype to implement the callback using something like "func IOServiceInterestCallback displayPowerNotificationsCallback { (...) } – JackPearse Jan 16 '15 at 15:45

1 Answers1

2

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

Community
  • 1
  • 1
Kirsteins
  • 27,065
  • 8
  • 76
  • 78
  • Thanks for this answer. That means I always need to use objC wrappers just for the callback. However, good to know that closures are not compatible with CFunctionPointer. – JackPearse Jan 19 '15 at 11:47