看了Horky同窗的《混合使用Objective-C,C++和Objective-C++》博文,我也有些想法也記錄一下,方便從此學習c++
1.Objective-C / C++ /C 深度混合不是一個好的選擇,易容出錯,也很差維護,當在Objective-C代碼中使用C++類時,咱們會使用等價的Objective-C類型和函數將C++代碼封裝(wrap)起來。函數
2.Objective-C頭文件中不要引用C++的頭文件,由於Objective-C中沒有class這個關鍵字. 編譯器會報Unknown type name 'class'; did you mean 'Class'?錯誤。學習
下面說一個列子方便理解url
//PlayerWindowController.h Objective-ct頭文件spa
#import <Cocoa/Cocoa.h>.net
@interface PlayerWindowController : NSWindowControllercode
{blog
@privateget
void *_player; //定義一個void *編譯器
}
- (BOOL) playURL:(NSURL *)url;
@end
//PlayerWindowController.mm 實現
#import "PlayerWindowController.h"
#include <libkern/OSAtomic.h> //c++ 頭文件
#include <AudioPlayer.h> //c++類頭文件
#include <AudioDecoder.h> //c++類頭文件
#define PLAYER (static_cast<AudioPlayer *>(_player))
static void decodingStarted(void *context, const AudioDecoder *decoder)
{
[(PlayerWindowController *)context decodingStarted:decoder];
}
static void renderingStarted(void *context, const AudioDecoder *decoder)
{
[(PlayerWindowController *)context renderingStarted:decoder];
}
static void renderingFinished(void *context, const AudioDecoder *decoder)
{
[(PlayerWindowController *)context renderingFinished:decoder];
}
@implementation PlayerWindowController
- (id) init
{
if(nil == (self = [super initWithWindowNibName:@"PlayerWindow"])) {
[self release];
return nil;
}
_player = new AudioPlayer();
return self;
}
- (BOOL) playURL:(NSURL *)url
{
AudioDecoder *decoder = AudioDecoder::CreateDecoderForURL(reinterpret_cast<CFURLRef>(url));
if(nullptr == decoder)
return NO;
PLAYER->Stop();
//註冊播放器開始/結束消息,方便UI界面更新
decoder->SetDecodingStartedCallback(decodingStarted, self);
decoder->SetRenderingStartedCallback(renderingStarted, self);
decoder->SetRenderingFinishedCallback(renderingFinished, self);
return YES;
}