在 Objective-C 类中混合 C 函数 [英] Mixing C functions in an Objective-C class

查看:41
本文介绍了在 Objective-C 类中混合 C 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 Objective-C 类,但它使用的是用 C 编写的 API.这基本上没问题,因为将 C 调用与 Objective-C 调用混合会导致很少的问题.

I am writing an Objective-C class but it uses an API written in C. This is mostly fine as mixing C calls with Objective-C calls causes few problems.

但是其中一个 API 调用需要回调方法(示例):

However one of the API call requires a call back method (example):

success = CFHostSetClient(host, MyCFHostClientCallBack, &context);

其中 MyCFHostClientCallBack 是一个 C 函数,定义如下:

Where MyCFHostClientCallBack is a C function defined like this:

static void MyCFHostClientCallBack(CFHostRef host, CFHostInfoType typeInfo, const CFStreamError *error, void *info);

  1. 能否/如何调用 Objective-C 方法来代替此方法?
  2. 我可以/应该将 C 函数与我的 Objective-C 调用混合使用吗?
  3. 如何将 C 函数与 Objective-C 方法混合使用?

推荐答案

混合 C 和 Objective-C 的方法和功能是可能的,这里是一个在 iPhone 应用程序中使用 SQLite API 的简单示例:(课程网站)

Mixing C and Objective-C methods and function is possible, here is a simple example that uses the SQLite API within an iPhone App: (course site)

下载 Zip 文件 (09_MySQLiteTableView.zip)压缩包)

C 函数需要在 Objective-C (.m) 文件中的 @implementation 之外声明.

C functions need to be declared outside of the @implementation in an Objective-C (.m) file.

int MyCFunction(int num, void *data)
{
     //code here...
}

@implementation

- (void)MyObjectiveCMethod:(int)number withData:(NSData *)data
{
      //code here
}

@end

因为 C 函数在 @implementation 之外,它不能调用像

Because the C function is outside of the @implementation it cannot call methods like

[self doSomething]

并且无法访问 ivars.

and has no access to ivars.

只要回调函数采用 userInfocontext 类型参数(通常为 void* 类型),就可以解决这个问题.这可用于将任何 Objective-C 对象发送到 C 函数.

This can be worked around as long as the call-back function takes a userInfo or context type parameter, normally of type void*. This can be used to send any Objective-C object to the C function.

示例代码,这可以用普通的 Objective-C 操作来操作.

As in the sample code, this can be manipulated with normal Objective-C operations.

另外请阅读这个答案:Mixing CObjective-C 类中的函数

这篇关于在 Objective-C 类中混合 C 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆