将函数作为Objective-C方法的参数传递

时间:2011-06-13 05:45:46

标签: objective-c function methods arguments

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

我一直在弄错语法。我该怎么做?

2 个答案:

答案 0 :(得分: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,在指定参数类型时(callback参数callFunction:}中没有指定回调的名称方法)。所以这个细节可能会让你失望,但这很简单。

答案 1 :(得分:2)

下面的代码工作,绝对没问题。请检查

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];
}