objective-c - 从 C 转换到 Objective-c

标签 objective-c xcode

我应该如何在 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/

相关文章:

ios - 如何将触摸事件传递给tableview下的另一个 View ?

ios - 每部分一个复选标记

ios - 从今天小部件打开密码屏幕

ios - 将 RSA 私钥加载到 EVP_PKEY

iphone - 错误的委托(delegate)声明

objective-c - 用户滚动时如何使右侧/腿部的图像居中

ios - swift:将 Haneke.framework 添加到 xcode 7.0.1 不起作用

iphone - 用于手指触摸绘图的 UIBezierPath 平滑曲线

Xcode 6/测试版 4 : using bridging headers with framework targets is unsupported

objective-c - 使用另一种语言的 Iphone 可本地化字符串