将objective-c类封装为c++类:最佳实践
Wrapping objective-c classes into c++ classes: best practices?
我有一个在objective-c++(.mm)文件中实现的c++类。这个类包含一些Cocoa对象,比如NSToolbar
,作为(私有)成员变量。该类应公开为纯c++接口,并可由纯c++客户端使用。换句话说,我正在尝试将obj-c对象包装在一个c++类中。
我想到的第一件事是在类接口中使用void指针然后每当_toolbar
需要被视为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文件中定义它;
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 ...
}
相关文章:
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- 在c代码之间共享数据的最佳方式
- 使用std::source_location报告错误的最佳实践
- 派生类销毁的最佳实践是什么
- 将寄存器设计成可由C和C++访问的外设的最佳实践
- 在两台机器之间进行时间戳的最佳c++chrono函数是什么
- 使用QQuickFramebufferObject时同步数据的最佳方式是什么
- 在C++中向零方向近似的最佳方法
- 使用不同的CRT将新的C++代码与旧的(二进制)组件隔离开来的最佳方法是什么
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- 如何将数组从Objective-C发送到C++函数
- 如果条件为TRUE(最佳方式?),则在do while循环中后置增量
- 检测win32服务创建和删除的最佳方法
- 在reactor中存储eventHandlers的最佳方式是什么
- 在Objective-C中,使用C#Protobuf-Net生成的“序列化Protobuf”的最佳方法是什么?
- 跨平台最佳 MVC 模型到控制器消息传递方法(C#、Objective-C++)
- Objective-C++对UI的绝对困惑;最佳实践
- 将objective-c类封装为c++类:最佳实践