在Objective-C类中混合C函数 [英] Mixing C functions in an Objective-C class
问题描述
但是,一个API调用需要回调方法(示例):
success = CFHostSetClient(host,MyCFHostClientCallBack,& ; context);
其中 MyCFHostClientCallBack
this:
static void MyCFHostClientCallBack(CFHostRef host,CFHostInfoType typeInfo,const CFStreamError * error,void * info);
- 如何将C函数与Objective-C方法混合? 如何将C函数与Objective-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);
- Can/How do I call an Objective-C method in place of this?
- Can/Should I mix C functions with my Objective-C calls?
- 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
orcontext
type parameter, normally of typevoid*
. 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屋!