views:

352

answers:

2

Hi,

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 :)

+4  A: 

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.

Frank Shearar
+2  A: 

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
maxbareis