问题描述
我在目标 C++ (.mm) 文件中实现了一个 C++ 类.这个类包含一些 Cocoa 对象,比如一个 NSToolbar
,作为(私有)成员变量.该类应该作为纯 c++ 接口公开,并且可由纯 c++ 客户端使用.换句话说,我试图将 obj-c 对象包装在 c++ 类中.
I have a c++ class implemented in a objective-c++ (.mm) file.This class contains some Cocoa object, say a NSToolbar
, as a (private) member variable.The class should be exposed as a pure c++ interface and usable by pure c++ clients.In other words, I am trying to wrap obj-c objects in a c++ class.
我首先想到的是在类接口中使用空指针然后在类实现中进行强制转换,只要 _toolbar
需要被视为 NSToolbar
.
The first thing that crosses my mind is to use a void pointer in the class interfaceand then work around with casting within the class implementation, whenever _toolbar
needs to be treated as a NSToolbar
.
例如我会有界面:
// NSToolbarWrapper.h
class NSToolbarWrapper {
private:
void * _toolbar;
//... rest of the class ...
}
和实现:
// NSToolbarWrapper.mm
...
ToolbarWrapper::ToolbarWrapper (...){
_toolbar = (__bridge void *)[[NSToolbar alloc] initWithIdentifier:@"My toolbar!"];
...
}
我不确定这是最聪明的方法.在这种情况下有最佳实践吗?
I am not sure this is the smartest approach.Is there a best practice in this case?
推荐答案
Pimpl idiom with c++ interface andobjective c++ implementation.如果您使用 unique_ptr 作为 pimpl,则需要声明析构函数并在 .mm 文件中定义它;
Pimpl idiom with c++ interface and objective c++ implementation.You'll need to declare your destructor and define it in the .mm file if you use unique_ptr as your pimpl;
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
这篇关于将objective-c 类包装到c++ 类中:最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!