Wrap target C in Objective C ++ / C ++

I have a C ++ application written using Boost / WXWidgets focused on Windows and Mac OSX. However, I have one problem that I cannot solve using these libraries. My solution requires me to wrap an Objective-C class so that I can call it from one of my C ++ modules. So far, my research tells me that I need to use Objective-C ++, written to source files with the extension .mm, which allows Xcode to treat the file as a combination of Objective-C and C ++. I found many articles detailing how to wrap C ++ so that it can be called from ObjectiveC, but nothing that gives any details on the back. Any links to articles or, even better, a processed example will be greatly appreciated.

+6
source share
3 answers

If you want to use reusable pure C ++ wrapper around the Objective-C class, Pimpl idiom works very well. The Pimpl idiom will make sure that there are no Objective C / Cocoa objects in the header file that will be included in pure C ++ code.

// FooWrapper.hpp // Absolutely no Cocoa includes or types here! class FooWrapper { public: int bar(); private: struct Impl; // Forward declaration Impl* impl; }; // FooWrapper.mm @import "FooWraper.hpp" @import "Foundation/NSFoo.h" struct FooWrapper::Impl { NSFoo* nsFoo; }; FooWrapper::FooWrapper() : impl(new Impl) { impl->nsFoo = [[NSFoo alloc] init]; } FooWrapper::~FooWrapper() { [impl->nsFoo release]; delete impl; } int FooWrapper::bar() { return [impl->nsFoo getInteger]; } 
+4
source

Just mix it up (but don't forget to tune the pool). He works.

  // obj-c code, in .mm file void functionContainingObjC(){ NSAutoreleasePool*pool=[[NSAutoreleasePool alloc] init]; [lots of brackets!]; [pool release]; } // c++ code, in .cc file functionContainingObjC(); 
+2
source

objc provides c-interfaces for basic interfaces and types ( #include <objc/headers_you_need.h> , so you can use these interfaces in pure c / C ++ TUs and then include libraries like Foundation or AppKit in mm and use objc types and messaging in the implementation.

the next one is a very simple interface that is not typical, but I recommend that you make it typeafe for the type of objc that you are wrapping. this should be enough to get started in the right direction.

 // .hpp namespace MON { // could be an auto pointer or a dumb pointer; depending on your needs class t_MONSubclassWrapper { public: // usual stuff here... // example wrapper usage: void release(); private: id d_objcInstance; }; } /* << MON */ // .mm ... #include <Foundation/Foundation.h> MON::t_MONSubclassWrapper::t_MONSubclassWrapper() : d_objcInstance([[MONSubclass alloc] init]) { } ... void MON::t_MONSubclassWrapper::release() { [d_objcInstance release]; } 
+1
source

Source: https://habr.com/ru/post/895491/


All Articles