2011-06-13 129 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

相關問題