Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Yes, that's easily possible, both ways, if you know a few tricks:</p> <p>1) The "id" type is actually defined in a plain C header. So you can do the following:</p> <p>In your header:</p> <pre><code>#include &lt;objc/objc.h&gt; class MyWindow { public: MyWindow(); ~MyWindow(); protected: id mCocoaWindow; }; </code></pre> <p>In your implementation (.mm):</p> <pre><code>#include "MyWindow.h" #include &lt;Cocoa/Cocoa.h&gt; MyWindow::MyWindow() { mCocoaWindow = [[NSWindow alloc] init]; } MyWindow::~MyWindow() { [mCocoaWindow release]; mCocoaWindow = nil; } </code></pre> <p>2) There are two preprocessor constants you can use to exclude C++/ObjC-specific code when a source file includes them that is one of the two, but not ObjC++:</p> <pre><code>#if __OBJC__ // ObjC code goes here. #endif /* __OBJC__*/ #if __cplusplus // C++ code goes here. #endif </code></pre> <p>Just be careful, you can't just add/remove ivars or virtual methods with an #ifdef, that will create two classes with different memory layouts and make your app crash in very weird ways.</p> <p>3) You can use a pointer to a struct without declaring its contents:</p> <p>In your header:</p> <pre><code>@interface MyCppObjectWrapper : NSObject { struct MyCppObjectWrapperIVars *ivars; // This is straight ObjC, no ++. } @end </code></pre> <p>In your implementation file (.mm):</p> <pre><code>struct MyCppObjectWrapperIVars { std::string myCppString1; std::string myCppString2; std::string myCppString3; }; @implementation MyCppObjectWrapper -(id) init { if(( self = [super init] )) { ivars = new MyCppObjectWrapperIVars; } return self; } -(void) dealloc { delete ivars; ivars = NULL; [super dealloc]; } @end </code></pre> <p>This will make your header simple standard C or ObjC, while your implementation file gets constructors/destructors of all ivars called without you having to create/delete each one as an object on the heap.</p> <p>This is all only the Mac side of things, but this would mean that you could keep the ObjC stuff out of your headers, or at least make it compile when used from cross-platform client files of the Mac implementation of your C++ portability layer.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload