objective-c - 如何在 swift 中编写 HID 函数 Handle_DeviceMatchingCallback?

标签 objective-c swift macos function hid

我有一个关于 HID 的程序。但它是用 Objective-C 编写的。这是一个项目,我的 friend 们只知道swift。所以我想将它转换为 swift,但我不知道如何编写该函数。

Obj-c 代码:

 /* Creating The HID Manager */
 IOHIDManagerRef manager = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
 /* Dictionary Matching - All the devices */
 IOHIDManagerSetDeviceMatching(manager,NULL);
 /* Connected and Disconnected Call Backs */
 IOHIDManagerRegisterDeviceMatchingCallback(manager,  &Handle_DeviceMatchingCallback , NULL);
 IOHIDManagerRegisterDeviceRemovalCallback(manager, &Handle_DeviceRemovalCallback,NULL);

回调函数是:

static void Handle_DeviceMatchingCallback(void *inContext,
                                          IOReturn inResult,
                                          void *inSender,
                                          IOHIDDeviceRef inIOHIDDeviceRef)
{
    printf("Connected\n");



}


static void Handle_DeviceRemovalCallback(void *inContext,
                                         IOReturn inResult,
                                         void *inSender,
                                         IOHIDDeviceRef inIOHIDDeviceRef)
{
    printf("Disconnected\n");
}

swift ,

我将 Handle_DeviceMatchingCallback() 写成

func Handle_DeviceMatchingCallback(inContext: UnsafeMutableRawPointer!, inResult: IOReturn, inSender: UnsafeMutableRawPointer!, inIOHIDDeviceRef: IOHIDDevice)
{
    print("Connected")
}

但我无法将函数传递给 IOHIDManagerRegisterDeviceMatchingCallback()

怎么做?

最佳答案

处理您的情况的一种方法是将回调作为闭包:

let Handle_DeviceMatchingCallback: IOHIDDeviceCallback = {context, result, sender, device in
    print("Connected")
}
let Handle_DeviceRemovalCallback: IOHIDDeviceCallback = {context, result, sender, device in
    print("Disconnected")
}

否则,您需要使用与 IOHIDDeviceCallback 中定义的签名完全相同的签名来声明回调函数。

typealias IOHIDDeviceCallback = (UnsafeMutableRawPointer?, IOReturn,
    UnsafeMutableRawPointer?, IOHIDDevice) -> Void

(摘自 Xcode 的快速帮助。)

func Handle_DeviceMatchingCallback(_ context: UnsafeMutableRawPointer?, _ result: IOReturn, _ sender: UnsafeMutableRawPointer?, _ device: IOHIDDevice) {
    print("Connected")
}
func Handle_DeviceRemovalCallback(_ context: UnsafeMutableRawPointer?, _ result: IOReturn, _ sender: UnsafeMutableRawPointer?, _ device: IOHIDDevice) {
    print("Disconnected")
}

关于objective-c - 如何在 swift 中编写 HID 函数 Handle_DeviceMatchingCallback?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41601721/

相关文章:

ios - 何时从 UITableViewCell 中删除 subview ?

ios - 根据条件将数组合并到字典中?

swift - 泛型是在编译期间专门化的,还是它们就像 java 泛型一样仅用于编译时检查?

java - 无法识别的虚拟机选项 'ShenandoahGCHeuristics=compact'

macos - 确定流程的架构

objective-c - 为什么 Objective-C block 在不将其复制到堆中的情况下仍然有效?

IOS/objective-C : Find Index of word in String

iphone - 具有 AND 和 OR 问题的 NSPredicate

ios - 将数据传递给之前的 View Controller VIPER

c++ - 错误 : "no member named ' uint8_t' in the global namespace"on MacOS