2011-06-13 18 views
5

Me gustaría pasar una función C como argumento de un método Objective-C, para luego actuar como una devolución de llamada. La función tiene el tipo int (*callback)(void *arg1, int arg2, char **arg3, char **arg4).Pasar la función como argumento al método Objective-C

Sigo recibiendo la sintaxis incorrecta. ¿Cómo hago esto?

+3

¿Podría mostrar lo que está utilizando en este momento? – nil

Respuesta

6

Como alternativa un poco más completa al ejemplo de 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; 
} 

Básicamente, es el mismo que cualquier otra cosa, excepto que sin el typedef, no se especifica el nombre de la devolución de llamada cuando se especifica el tipo del parámetro (el parámetro callback en el método callFunction:). Así que ese detalle podría haberlo estado haciendo tropezar, pero es bastante simple.

+0

Derecha - Me faltaba la declaración typedef. Gracias. – SK9

2

El siguiente fragmento de código funcionó, absolutamente bien. sólo echa

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

Derecha - Me faltaba la declaración typedef. Gracias. – SK9

Cuestiones relacionadas