2010-03-07 50 views
3

我正在使用一個C++庫使用回調通知有關操作的進度。 一切工作正常,除了這個: 我需要在我的控制器中有一個函數作爲C++回調函數使用。 我已經嘗試了很多東西,但都沒有工作。Iphone,回調和目標c

你知道我們怎麼能管理這種事情嗎?

謝謝:)

+0

更多細節請:您嘗試了哪些方法? – 2010-03-07 18:09:45

回答

3

你必須在你的.h中用你的回調方法定義一個C++類,實現C++接口。這個類還保留了objC類的代理。

在你的.m文件中@end指定了C++方法。然後,您可以使用委託在.H

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

在.M

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

iPhone API,如音頻隊列服務使用其回調一個void *參數,可以在其中收起你的Objective-C的實例。

如果你的C++庫有一個類似的設置 - 你的回調提供了一個void *「上下文」參數 - 你可以這樣做:

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

所以你使用inClientData來存儲您的實例,然後可以調用方法在那個做實際處理的實例上。