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

SK9*_*SK9 6 methods arguments function objective-c

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

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

nil*_*nil 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;
}
Run Code Online (Sandbox Code Playgroud)

基本上,它与其他任何东西都是一样的,除了没有typedef,在指定参数类型(callback任一callFunction:方法中的参数)时,不指定回调的名称.所以这个细节可能会让你失望,但这很简单.