AP.
AP.

Reputation: 5323

Iphone, callback and objective c

I am using a c++ library using callback to inform about the progress of an operation. Everything is working fine except this: I need to have a function in my controller to be use as a c++ callback function. I've tried a lot of things but none of them are working.

Do you know how we can manage this kind of thing?

Thanks :)

Upvotes: 3

Views: 3110

Answers (3)

Frank Shearar
Frank Shearar

Reputation: 17132

iPhone APIs like the Audio Queue Services use a void * parameter in their callbacks, into which you can stuff your Objective-C instance.

If your C++ library has a similar setup - your callback gives a void * "context" parameter - you could do this:

void interruptionListener(void *inClientData, UInt32 inInterruptionState) {
  InterruptionMonitor *self = (InterruptionMonitor *)inClientData;
  [self inInterruption: inInterruptionState == kAudioSessionBeginInterruption];
}

So you use the inClientData to store your instance, and can then call methods on that instance that do the actual processing.

Upvotes: 5

Alex Kremer
Alex Kremer

Reputation: 2311

There is a much better way of doing this. If you are already using boost in your iOS project you can use my objc_callback template: http://alex.tapmania.org/2012/04/c-to-obj-c-callbacks-part-2.html

Upvotes: 2

maxbareis
maxbareis

Reputation: 886

You have to define a c++-class in your .h with your callback methods, implementing the c++-interface. This class also keeps a delegate of your objC Class.

in your .m File after @end you specify the c++ methods. You may then use the delegate to perform selectors of your objC class

in .h

@interface YourObjcClass {
#ifdef __cplusplus
    class FooObserver : public YourNS::Interface {
    public:
        virtual ~FooObserver() {
        }
        YourObjcClass *delegate;
        };
YourNS::YourCallbackClass *myCallbackClass;
#endif

in .m

#ifdef __cplusplus
void FooObserver::callback( args ) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
[delegate performSelectorOnMainThread:@selector(performCallback) 
                   withObject:nil 
                waitUntilDone:false];
[pool release];
}
#endif

Upvotes: 3

Related Questions