如何在 swift 中将 nil 转换为 IOKit.IOHIDValueCallback

How to cast nil to IOKit.IOHIDValueCallback in swift

我在 swift 中编写了一个小实用程序,它使用 IOHIDManagerRegisterInputValueCallback 注册了一个回调。我正在努力成为一个好公民并清理自己。

[文档] (https://developer.apple.com/library/content/documentation/DeviceDrivers/Conceptual/HID/new_api_10_5/tn2187.html#//apple_ref/doc/uid/TP40000970-CH214-SW61) 说要注销应该用 Null

调用注册函数

Note: To unregister pass NULL for the callback.

不幸的是

IOHIDManagerRegisterInputValueCallback( hidManager, nil , nil);

不编译说:

Nil is not compatible with expected argument type 'IOHIDValueCallback' (aka '@convention(c) (Optional, Int32, Optional, IOHIDValue) -> ()')

如何将 nil 转换为正确的类型?

这是一个应该编译的示例代码:

import Foundation
import Carbon
import IOKit
import IOKit.usb
import IOKit.hid
class IOEventManager{
  func start()->Void{
    let hidManager = IOHIDManagerCreate( kCFAllocatorDefault, IOOptionBits(kIOHIDOptionsTypeNone) );
    let context = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque());
    IOHIDManagerRegisterInputValueCallback( hidManager, nil, context);
  }
}

如果你想要一个完整的项目,请查看 https://github.com/jeantil/autokbisw and look at IOKeyEventMonitor#deinit

很长一段时间后,我再次打开该项目并再次细读方法签名,我注意到 swift 绑定的签名实际上需要一个 IOHIDValueCallback?,这意味着一个可选的 IOHIDValueCallback

@available(OSX 10.5, *)
public func IOHIDManagerRegisterInputValueCallback(_ manager: IOHIDManager, _ callback: IOKit.IOHIDValueCallback?, _ context: UnsafeMutableRawPointer?)

这对我来说不是很明显,因为您可以在调用方法时直接传递 IOHIDValueCallback 值而无需显式换行。

注意到这一点使解决方案显而易见:

IOHIDManagerRegisterInputValueCallback( hidManager, Optional.none , context);

程序现在可以编译并且运行正常。