2008-08-22
■[Objective-C++] Objective-CのクラスをC++でラップする方法
Objective-C と C++ のコードは、 *.mm 形式のファイルの中では混在させることができます。
なので、 Objective-C のライブラリを C++ でラップしてしまえば、ほとんどが C++ で組めるようになります。
以下はその方法
*.h では混在コードを書けないので、 C++ のクラスのメンバとして
Objective-C のオブジェクトを持つには PImplイディオム を使用します。
Cpp.h
#ifndef CPP_INCLUDE #define CPP_INCLUDE #include <boost/shared_ptr.hpp> class CppHoge { struct Impl; boost::shared_ptr<Impl> pImpl_; public: CppHoge(); ~CppHoge(); void doSomething(); }; #endif // CPP_INCLUDE
Cpp.mm
#include "Cpp.h" struct CppHoge::Impl { NSString *str; // Objective-C のオブジェクト }; CppHoge::CppHoge() : pImpl_(new Impl) { pImpl_->str = [[NSString alloc] init]; } CppHoge::~CppHoge() { [pImpl_->str release]; } void CppHoge::doSomething() { int length = [pImpl_->str length]; }
次に、 Objective-C のクラスメンバで C++ のオブジェクトを持つためにはポインタを使用します。
(コンストラクタ/デストラクタではなく、 init/dealloc を使用するため)
ObjCpp.h
#include "Cpp.h" @interface ObjCpp : NSObject { CppHoge *cppHoge_; } @end
ObjCpp.mm
#import "ObjCpp.h" @implementation ObjCpp - (id)init { if (self = [super init]) { cppHoge_ = new CppHoge; } return self; } - (void)doSomething { cppHoge_->doSomething(); } - (void)dealloc { delete cppHoge_; [super dealloc]; } @end
トラックバック - http://d.hatena.ne.jp/faith_and_brave/20080822/1219396399
リンク元
- 19 http://www.google.com/search?hl=ja&lr=lang_ja&ie=UTF-8&oe=UTF-8&q=wstring+atoi&num=50
- 8 http://www.google.co.jp/search?hl=ja&client=firefox-a&rls=org.mozilla:ja:official&hs=3cn&q=CString+MFC+std::string&btnG=検索&lr=lang_ja
- 7 http://cpp.ring.hatena.ne.jp/
- 6 http://d.hatena.ne.jp/
- 6 http://www.google.co.jp/search?sourceid=navclient&hl=ja&ie=UTF-8&rlz=1T4GGIH_jaJP283JP284&q=C+++lexical_cast
- 5 http://r.hatena.ne.jp/gamaguchi/
- 5 http://www.google.co.jp/reader/view/
- 3 http://a.hatena.ne.jp/melpon/
- 3 http://clip.livedoor.com/clips/umesue
- 3 http://reader.livedoor.com/reader/