2011-06-13 130 views
5

我想将一个C函数作为参数传递给Objective-C方法,然后将其作为回调函数。该函数的类型为int (*callback)(void *arg1, int arg2, char **arg3, char **arg4)将函数作为参数传递给Objective-C方法

我一直听错语法。我该怎么做呢?

+3

你能告诉你现在正在使用什么吗? – nil 2011-06-13 05:53:49

回答

6

至于KKK4SO的例子稍微完整的备选方案:

#import <Cocoa/Cocoa.h> 

// typedef for the callback type 
typedef int (*callbackType)(int x, int y); 

@interface Foobar : NSObject 
// without using the typedef 
- (void) callFunction:(int (*)(int x, int y))callback; 
// with the typedef 
- (void) callFunction2:(callbackType)callback; 
@end 

@implementation Foobar 
- (void) callFunction:(int (*)(int x, int y))callback { 
    int ret = callback(5, 10); 
    NSLog(@"Returned: %d", ret); 
} 
// same code for both, really 
- (void) callFunction2:(callbackType)callback { 
    int ret = callback(5, 10); 
    NSLog(@"Returned: %d", ret); 
} 
@end 

static int someFunction(int x, int y) { 
    NSLog(@"Called: %d, %d", x, y); 
    return x * y; 
} 

int main (int argc, char const *argv[]) { 
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 

    Foobar *baz = [[Foobar alloc] init]; 
    [baz callFunction:someFunction]; 
    [baz callFunction2:someFunction]; 
    [baz release]; 

    [pool drain]; 
    return 0; 
} 

基本上,它是同别的,只是没有typedef的,你没有指定的名称在指定参数类型(callFunction:方法中的参数callback)时回调。所以这个细节可能会让你失望,但它很简单。

+0

对 - 我错过了typedef声明。谢谢。 – SK9 2011-06-13 06:15:48

2

以下peice代码工作,绝对好。只是检查

typedef int (*callback)(void *arg1, int arg2, char **arg3, char **arg4); 

int f(void *arg1, int arg2, char **arg3, char **arg4) 
{ 
    return 9; 
} 

-(void) dummy:(callback) a 
{ 
    int i = a(NULL,1,NULL,NULL); 
    NSLog(@"%d",i); 
} 

-(void) someOtherMehtod 
{ 
    callback a = f; 
    [self dummy:a]; 
} 
+0

对 - 我遗漏了typedef声明。谢谢。 – SK9 2011-06-13 06:15:58

相关问题