看了Horky同学的《混合使用Objective-C,C++和Objective-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‘?错误。
下面说一个列子方便理解
//PlayerWindowController.h Objective-ct头文件
#import <Cocoa/Cocoa.h>
@interface PlayerWindowController : NSWindowController
{
@private
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;
}