oip*_*tar 16 c function-pointers objective-c
我正在编写一个使用C库的Objective-C应用程序.我目前面临的问题是C库有一个结构,其中某些字段是稍后用作回调的函数指针.如何将Objective-C实例方法转换为函数指针并将其传递给库?
tro*_*foe 19
您需要在Objective-C类实现文件中提供C回调函数,这仅在回调能够使用某种上下文指针时才有效.
所以想象一下C回调签名是这样的:
void myCallback(void *context, int someOtherInfo);
Run Code Online (Sandbox Code Playgroud)
然后在Objective-C类实现文件中,您需要使用该回调将trampoline返回到Objective-C类(使用上下文指针作为要调用的类的实例):
// Forward declaration of C callback function
static void theCallbackFunction(void *context, int someOtherInfo);
// Private Methods
@interface MyClass ()
- (void)_callbackWithInfo:(int)someOtherInfo;
@end
@implementation MyClass
- (void)methodToSetupCallback
{
// Call function to set the callback function, passing it a "context"
setCallbackFunction(theCallbackFunction, self);
...
}
- (void)_callbackWithInfo:(int)someOtherInfo
{
NSLog(@"Some info: %d", someOtherInfo);
}
@end
static void theCallbackFunction(void *context, int someOtherInfo)
{
MyClass *object = (MyClass *)context;
[object _callbackWithInfo:someOtherInfo];
}
Run Code Online (Sandbox Code Playgroud)
如果你的C回调函数不接受某种上下文信息,那么:
MyClass为一个!| 归档时间: |
|
| 查看次数: |
2902 次 |
| 最近记录: |