I found an example for IOKit
:
我找到了IOKit的一个例子:
var notification:io_object_tlet matching:NSDictionary = IOServiceNameMatching("IODisplayWrangler").takeRetainedValue()let displayWrangler = IOServiceGetMatchingService(kIOMasterPortDefault, matching)let notificationPort = IONotificationPortCreate(kIOMasterPortDefault) IOServiceAddInterestNotification(notificationPort, displayWrangler, kIOGeneralInterest, displayPowerNotificationsCallback, nil, ¬ification)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.
上面的例子对我来说很清楚 - 到目前为止。但是IOServiceAddInteresNotification想要一个回调函数。通过在.m文件中的某个位置实现C-Style功能,这很简单。
The documentation says that I have to use a callback of type IOServiceInterestCallback
.
文档说我必须使用IOServiceInterestCallback类型的回调。
In C-Style it is defined as follows:
在C风格中,它定义如下:
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?
在objC上,一切似乎都很完美。什么是swift中的等效解决方案?如何在不为此创建C或objC文件的情况下声明回调函数?
Any ideas?
Cheers,
Jack
1 个解决方案
#1
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
你不能在Swift中创建类似回调的C函数,因为闭包与CFunctionPointer不兼容。您可以在Objective-C或C中实现一些解决方法。示例在Objective-C Wrapper中描述,用于CFunctionPointer到Swift Closure
#1
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
你不能在Swift中创建类似回调的C函数,因为闭包与CFunctionPointer不兼容。您可以在Objective-C或C中实现一些解决方法。示例在Objective-C Wrapper中描述,用于CFunctionPointer到Swift Closure