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

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

问题描述

我写了一个Objective-C类,但它使用一个用C编写的API。这是很好的,因为混合C调用与Objective-C调用几乎没有问题。



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

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

其中 MyCFHostClientCallBack this:

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




    可以/如何调用Objective-C方法
  1. 如何将C函数与Objective-C方法混合?
  2. 如何将C函数与Objective-C调用混合?


解决方案

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



http://stanford.edu/class/cs193p/cgi-bin/drupal/system/files/sample_code/09_MySQLiteTableView.zip



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

  int MyCFunction(int num,void * data)
{
//代码在这里...
}

@实现

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

@end

因为C函数在 @implementation 它不能调用

  [self doSomething] 



并且无法访问ivars。



-back函数接受 userInfo 上下文类型参数,通常类型为 void * code>。这可以用于将任何Objective-C对象发送到C函数。



示例代码,这可以使用正常的Objective-C操作来操作。



另外,请阅读这个答案:在Objective-C类中混合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.

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

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

Where MyCFHostClientCallBack is a C function defined like this:

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

  1. Can/How do I call an Objective-C method in place of this?
  2. Can/Should I mix C functions with my Objective-C calls?
  3. How do I mix C functions with Objective-C methods?

解决方案

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)

http://stanford.edu/class/cs193p/cgi-bin/drupal/system/files/sample_code/09_MySQLiteTableView.zip

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

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

[self doSomething]

and has no access to ivars.

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.

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

In addition please read this answer: Mixing C functions in an Objective-C class

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

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