繁体   English   中英

将Objective-C类包装到C ++类中:最佳实践?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM