[英]Wrapping objective-c classes into c++ classes: best practices?
我有一個在目標C ++(.mm)文件中實現的c ++類。 此類包含一些Cocoa對象,例如NSToolbar
,作為(私有)成員變量。 該類應作為純c ++接口公開,並且可由純c ++客戶端使用。 換句話說,我正在嘗試將obj-c對象包裝在c ++類中。
我想到的第一件事是,在需要將_toolbar
視為_toolbar
時,在類接口中使用void指針,然后在類實現中進行NSToolbar
。
例如,我將具有以下接口:
// NSToolbarWrapper.h
class NSToolbarWrapper {
private:
void * _toolbar;
//... rest of the class ...
}
和實現:
// NSToolbarWrapper.mm
...
ToolbarWrapper::ToolbarWrapper (...){
_toolbar = (__bridge void *)[[NSToolbar alloc] initWithIdentifier:@"My toolbar!"];
...
}
我不確定這是最明智的方法。 在這種情況下是否有最佳實踐?
具有c ++接口和目標c ++實現的Pimpl習慣用法。 如果您使用unique_ptr作為pimpl,則需要聲明析構函數並在.mm文件中定義它;
class.h:
class myclass {
class impl;
std::unique_ptr<impl> _impl; // or shared_ptr if you want shared handle behaviour
public:
myclass(const char* s);
~myclass(); // only declare here
};
class.mm:
class myclass::impl {
NSString* _str;
public:
impl(const char* s)
: _str([NSString stringWithCString:s encoding: NSASCIIStringEncoding])
{}
};
myclass::myclass(const char* s)
: _impl(new impl(s))
{}
myclass::~myclass() = default; // define here
為了便於記錄,並在以后提醒自己。
我看到了一個非常著名的開源庫,它看起來像這樣,這似乎是一種有效的方法:
// NSToolbarWrapper.h
#ifdef __OBJC__
typedef NSToolbar *Toolbar;
#else
typedef class NSToolbar_opaque *Toolbar;
#endif // __OBJC__
class NSToolbarWrapper {
private:
Toolbar _toolbar;
//... rest of the class ...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.