Hen*_*rik 3 types callback iokit cfrunloop swift
我正在尝试订阅 macOS 上电源状态的更改。我发现有一种使用 IOKit 的方法,尽管它有点复杂。我需要#import <IOKit/ps/IOPowerSources.h>在 ObjC 桥接标头中使用它来导入它。然后我可以访问函数 IOPSNotificationCreateRunLoopSource,其签名为:
IOPSNotificationCreateRunLoopSource(_ callback: IOPowerSourceCallbackType!, _ context: UnsafeMutablePointer<Void>!) -> Unmanaged<CFRunLoopSource>!
Run Code Online (Sandbox Code Playgroud)
我从Callback method to Apple run Loop的答案中得到了一些帮助,但仍然无法IOPowerSourceCallbackType在 Swift 中创建类型的函数。编译此程序时缺少什么?
问题是这IOPowerSourceCallbackType是一个C 函数。
根据苹果的文档,这些函数可以作为闭包使用:
C 函数指针以 C 函数指针调用约定作为闭包导入到 Swift 中
所以最简单的方法是使用闭包:
IOPSNotificationCreateRunLoopSource({ (context: UnsafeMutableRawPointer?) in
debugPrint("Power source changed")
}, &context)
Run Code Online (Sandbox Code Playgroud)
第二种选择是使用顶级函数:
func powerSourceChanged(arg: UnsafeMutableRawPointer?) {
debugPrint("Power source changed")
}
IOPSNotificationCreateRunLoopSource(powerSourceChanged, &context)
Run Code Online (Sandbox Code Playgroud)
作为参考,我如何使用它的完整实现:
class WindowController: NSWindowController {
static var context = 0
override func windowDidLoad() {
super.windowDidLoad()
let loop: CFRunLoopSource = IOPSNotificationCreateRunLoopSource({ (context: UnsafeMutableRawPointer?) in
debugPrint("Power source changed")
}, &WindowController.context).takeRetainedValue() as CFRunLoopSource
CFRunLoopAddSource(CFRunLoopGetCurrent(), loop, CFRunLoopMode.defaultMode)
}
}
Run Code Online (Sandbox Code Playgroud)
更新
为了让它与设置循环的实例交互,您必须作为self上下文传递,但self不是指针。
当您尝试self通过在前面添加&( &self) 作为指针传递时,您将收到一个不可变的错误self。
要将其转换为不透明指针,您可以使用该类Unmanaged:
let opaque = Unmanaged.passRetained(self).toOpaque()
Run Code Online (Sandbox Code Playgroud)
然后可以用作UnsafeMutableRawPointer:
let context = UnsafeMutableRawPointer(opaque)
Run Code Online (Sandbox Code Playgroud)
我们可以使用什么作为 的上下文IOPSNotificationCreateRunLoopSource。
然后在回调中,通过Unmanaged再次使用该类,我们可以将此指针解析回其初始实例:
let opaque = Unmanaged<WindowController>.fromOpaque(context!)
let _self = opaque.takeRetainedValue()
Run Code Online (Sandbox Code Playgroud)
完整示例:
func PowerSourceChanged(context: UnsafeMutableRawPointer?) {
let opaque = Unmanaged<WindowController>.fromOpaque(context!)
let _self = opaque.takeRetainedValue()
_self.powerSourceChanged()
}
class WindowController: NSWindowController {
override func windowDidLoad() {
super.windowDidLoad()
let opaque = Unmanaged.passRetained(self).toOpaque()
let context = UnsafeMutableRawPointer(opaque)
let loop: CFRunLoopSource = IOPSNotificationCreateRunLoopSource(
PowerSourceChanged,
context
).takeRetainedValue() as CFRunLoopSource
CFRunLoopAddSource(CFRunLoopGetCurrent(), loop, CFRunLoopMode.defaultMode)
}
func powerSourceChanged() {
debugLog("Power source changed")
}
}
Run Code Online (Sandbox Code Playgroud)
奖金