如何使用 swift 实现 C 样式回调函数



我找到了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);

上面的例子对我来说很清楚 - 到目前为止。但是IOServiceAddInteresNotification想要一个回调函数。通过实现 .m -file 中某处的 C 样式函数来做到这一点很简单。

文档说我必须使用类型 IOServiceInterestCallback 的回调。

在 C 样式中,它的定义如下:

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

在 objC 上,一切似乎都很完美。swift 中的等效解决方案是什么?如何在不为此创建 C 或 objC 文件的情况下声明回调函数?

有什么想法吗?

干杯

千斤顶

你不能像 Swift 中的回调那样创建 C 函数,因为闭包与CFunctionPointer不兼容。你可以在 Objective-C 或 C 中实现一些解决方法.示例在 Objective-C Wrapper for CFunctionPointer to a Swift Closure 中描述

最新更新