2

我应该如何在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
{
  .....
}

我不确定它是否正确。

4

1 回答 1

3

简短的回答是:你不能直接这样做。

这是因为 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
                                          );        

}
于 2013-02-20T11:56:25.367 回答