7

I'd like to pass a C function as an argument to an Objective-C method, to then act as a callback. The function has type int (*callback)(void *arg1, int arg2, char **arg3, char **arg4).

I keep getting the syntax wrong. How do I do this?

1
  • 3
    Could you show what you're using right now? Commented Jun 13, 2011 at 5:53

2 Answers 2

8

As a slightly more complete alternative to KKK4SO's example:

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

Basically, it's the same as anything else, except that without the typedef, you don't specify the name of the callback when specifying the type of the parameter (the callback parameter in either callFunction: method). So that detail might have been tripping you up, but it's simple enough.

Sign up to request clarification or add additional context in comments.

1 Comment

Right - I was missing the typedef declaration. Thanks.
3

The following peice of code worked,absolutely fine . just check

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

1 Comment

Right - I was missing the typedef declaration. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.