gpt4 book ai didi

objective-c - objective-c /c : Detect USB drive via IOKit only on Mac

转载 作者:搜寻专家 更新时间:2023-10-30 20:09:38 27 4
gpt4 key购买 nike

这是我的代码,它会在我第一次运行应用程序时检测到设备,但在运行后它不会检测到新设备。

//Just for testing
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
[self detectUSB];
}

void detectUSB()
{
//dictionary
CFMutableDictionaryRef matchingDict = matchingDict = IOServiceMatching(kIOUSBDeviceClassName);

//create notification
IONotificationPortRef notificationObject; //notification object to listen
mach_port_t masterPort = 0; //received from IOMasterPort
notificationObject = IONotificationPortCreate(masterPort);

//create run loop
CFRunLoopSourceRef notificationRunLoopSource;

//use notification obejct received from notificationPortCreate
notificationRunLoopSource = IONotificationPortGetRunLoopSource(notificationObject);

CFRunLoopAddSource(CFRunLoopGetCurrent(), notificationRunLoopSource, kCFRunLoopDefaultMode);

IOServiceAddMatchingNotification(notificationObject,kIOFirstMatchNotification, matchingDict,isAttached,(__bridge void*)self,&iter );

isAttached(NULL, iter);
}

void isAttached(void *refcon, io_iterator_t iterator) {

io_service_t usbDevice;
while((usbDevice = IOIteratorNext(iterator))) {
io_name_t name;
IORegistryEntryGetName(usbDevice, name);
printf("\tName:\t\t%s\n", (char *)name);

CFNumberRef idProduct = (CFNumberRef)IORegistryEntrySearchCFProperty(usbDevice, kIOServicePlane, CFSTR("idProduct"), kCFAllocatorDefault, 0);
uint16_t PID;
CFNumberGetValue(idProduct, kCFNumberSInt16Type, (void *)&PID);
printf("\tidProduct:\t0x%x\n", PID);

IOObjectRelease(usbDevice);
CFRelease(idProduct);
}
IOObjectRelease(iterator);
}

此外,如果我拔下其中一个 USB 驱动器,我应该如何检测它?要不要再加一个

  IOServiceAddMatchingNotification(notificationObject,kIOFirstMatchNotification, matchingDict,isDetached,(__bridge void*)self,&iter );

在 isAttached 函数之后?实际上我添加了但它给了我错误的访问错误。你们能告诉我如何处理这些问题吗?谢谢!!

最佳答案

问题在于您的处理程序函数中的 IOObjectRelease() 调用。只要您想接收这些通知,就需要保留从 IOServiceAddMatchingNotification 获得的迭代器。如果您删除发布调用,代码将正常工作。

关于您的第二个问题:调用给出了错误的访问错误,因为 matchingDictIOServiceAddMatchingNotification 释放。如果您在该调用之前执行了 CFRetain(matchingDict),则可以使用相同的匹配字典添加第二个 Notification。 (顺便说一句:如果您对设备移除通知感兴趣,您应该传递 kIOTerminatedNotification 而不是 kIOFirstMatchNotification

关于objective-c - objective-c /c : Detect USB drive via IOKit only on Mac,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17305260/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com