我应该如何在 Objective-C 中编写这段代码:
kr = IOServiceAddMatchingNotification(gNotifyPort,
kIOFirstMatchNotification, matchingDict, RawDeviceAdded, NULL, &gRawAddedIter);
我尝试过这个:
kr = IOServiceAddMatchingNotification(gNotifyPort, kIOFirstMatchNotification,
matchingDict, @selector(RawDeviceAdded), NULL, &gRawAddedIter);
该函数如下所示:
(void)RawDeviceAdded:(void *)refCon iterator:(io_iterator_t)iterator
{
.....
}
不知道是否正确。
最佳答案
简短的回答是:你不能直接这样做。
这是因为 IOKit 是一个 C-API,因此它需要的任何回调函数都必须是 C 语言,而不是 Objective-C。
这并不是说您不能混合使用 C 和 Objective-C,并使用 C 回调函数来蹦床到您的 Objective-C 方法。只需获取对 C 回调函数的类的引用即可;在这种特殊情况下,使用的是 refCon
。
SomeObjcClass.m:
// Objective-C method (note that refCon is not a parameter as that
// has no meaning in the Objective-C method)
-(void)RawDeviceAdded:(io_iterator_t)iterator
{
// Do something
}
// C callback "trampoline" function
static void DeviceAdded(void *refCon, io_iterator_t iterator)
{
SomeObjcClass *obj = (SomeObjcClass *)refCon;
[obj RawDeviceAdded:iterator];
}
- (void)someMethod
{
// Call C-API, using a C callback function as a trampoline
kr = IOServiceAddMatchingNotification(gNotifyPort,
kIOFirstMatchNotification,
matchingDict,
DeviceAdded, // trampoline function
self, // refCon to trampoline
&gAddedIter
);
}
关于objective-c - 从 C 转换到 Objective-c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14979040/