2014-10-01 2 views
2

나는 objective-C++ (.mm) 파일로 구현 된 C++ 클래스를 사용하고 있습니다. 이 클래스는 코코아 객체 (예 : NSToolbar)를 (개인) 멤버 변수로 포함합니다. 클래스는 순수한 C++ 인터페이스로 노출되어야하며 순수한 C++ 클라이언트에서 사용할 수 있어야합니다. 즉, 나는 C++ 클래스에서 obj-c 객체를 래핑하려고합니다. 내 마음을 교차objective-c 클래스를 C++ 클래스로 래핑하는 것이 가장 좋습니다.

우선 클래스 인터페이스 의 무효 포인터를 사용하고 _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!"]; 
... 
} 

나는 이것이 가장 현명한 방법입니다 확실하지 않다

예를 들어 나는 인터페이스를 가질 것이다. 이 경우 모범 사례가 있습니까?

+0

클래스를 선언 할 때 pimpl 관용구를 사용하는 것입니다 순수한 C++에 노출 될 것입니다. –

답변

3

C++ 인터페이스 및 객관적인 C++ 구현을 사용하는 PIMPL 관용구. unique_ptr을 사용하는 경우 소멸자를 선언하고 .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 
0

, 그리고 미래의 자신을 생각 나게. 나는 또한 유효한 방법이 될 것 같은 일을 꽤 잘 알려진 오픈 소스 라이브러리, 본

: 내가 가장 좋은 방법을 발견했다

// NSToolbarWrapper.h 
#ifdef __OBJC__ 
typedef NSToolbar *Toolbar; 
#else 
typedef class NSToolbar_opaque *Toolbar; 
#endif // __OBJC__ 

class NSToolbarWrapper { 
private: 
Toolbar _toolbar; 

//... rest of the class ... 

} 
관련 문제