【发布时间】:2017-02-14 11:30:57
【问题描述】:
我一直在阅读有关 Objective-C 块的内容(例如,在 Apple documentation、a blog post 和 one 或 two 或 three Stack Overflow 答案中)。我想将 C/C++ 风格的回调传递给 Objective-C 方法。
这是我在 C/C++ 方面的声明
#ifdef __cplusplus
extern "C" {
#endif
typedef void (*CALCULATION_CALLBACK)(int x);
void setCubeCallback(int x, CALCULATION_CALLBACK callback);
#ifdef __cplusplus
}
#endif
在 Objective-C 中
@interface IOSPluginTest : NSObject
typedef void (^CalculationHandler)(int x);
-(void)cubeThisNumber:(int)number andCallbackOn:(CalculationHandler)callback;
@end
这就是 Objective-C 的实现
#import "IOSPluginTest.h"
@implementation IOSPluginTest
-(void)cubeThisNumber:(int)number andCallbackOn:(CalculationHandler)callback {
int result = number * number * number;
if (callback != nil) {
callback(result);
}
}
@end
最后一点出错了,C/C++ 实现
void setCubeCallback(int x, CALCULATION_CALLBACK callback) {
[[[IOSPluginTest alloc] init] cubeThisNumber:x andCallbackOn:callback];
}
编译失败,报错
将“CALCULATION_CALLBACK”(又名“void(*)(int)”)发送到不兼容类型“CalculationHandler”(又名“void(^)(int)”)的参数
void(*)(int) 和 void(^)(int) 这两种类型的描述和我很相似;我错过了什么?
【问题讨论】:
标签: objective-c