从 IOKit (CoreFoundation) 接收插入设备的通知时出现问题

And*_*ndi 4 usb iokit core-foundation xcode4

我目前正在 10.6.7 上开发一个应用程序,当插入新的 USB 设备时,它应该收到通知。我发现有一个 IOKit 函数可以处理“IOServiceAddMatchingNotification”等内容。因为这个特定函数的返回值是 0,所以我认为问题可能出在我的匹配字典中,该字典被赋予这个函数。我这样声明字典:

CFMutableDictionaryRef matchingDict = IOServiceMatching(kIOUSBDeviceClassName);
Run Code Online (Sandbox Code Playgroud)

因为我不想收到每个设备的通知,所以我不知道这是否是创建这个特定词典的正确方法。

我的完整代码如下所示:

ioKitNotificationPort = IONotificationPortCreate(kIOMasterPortDefault);
notificationRunLoopSource = IONotificationPortGetRunLoopSource(ioKitNotificationPort);

CFRunLoopAddSource(CFRunLoopGetCurrent(), notificationRunLoopSource, kCFRunLoopDefaultMode);

CFMutableDictionaryRef matchingDict = IOServiceMatching(kIOUSBDeviceClassName);


addMatchingNotificationResult = IOServiceAddMatchingNotification(ioKitNotificationPort,
                                                                 kIOPublishNotification,
                                                                 matchingDict,
                                                                 deviceAdded,
                                                                 NULL,
Run Code Online (Sandbox Code Playgroud)

有谁知道为什么这行不通?(注意:Callback 函数是一个 static void c 函数,其余部分包装在 Obj-C 类中)。

谢谢

Xcode 4, 10.6.7

Mat*_*tie 5

奇怪的是,在通知被武装之前,您必须清空 IOServiceAddMatchingNotification 返回的迭代器。我在提供的代码中没有看到这一点,因此这可能是问题所在。实际上,您需要保留该迭代器来保持通知运行。

io_iterator_t ioNotification;

addMatchingNotificationResult = IOServiceAddMatchingNotification(ioKitNotificationPort,
                                                                 kIOPublishNotification,
                                                                 matchingDict,
                                                                 deviceAdded,
                                                                 NULL,
                                                                 &ioNotification);

while ((service = IOIteratorNext(ioNotification)))
{
    NSLog(@"Hey, I found a service!");

    IOObjectRelease(service); // yes, you have to release this
}
Run Code Online (Sandbox Code Playgroud)