我有一个关于 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/