Recommended way to use C ++ class in Objective-C class, minimizing the use of Objective-C ++?

I am mixing Objective-C and C ++. However, I want to minimize the use of Objective-C ++. Since it has some limitations in both Objective-C and C ++.

I am currently using it like this.

// Ah, Objective-C #import "Bh" @interface A { B* b; } @end // Bh, Objective-C++ @interface B { void* c; } // Ch, C++ class C { }; 

I want to include Ch in Bh , but if I did, Bh could not be imported into Ah . So I have to leave the variable c as void* . This is not a big problem, because I can freely use the members of c in Bm . But I always have to leave him. It feels something incomprehensible. So I want to use the best way, if that is the case.

+7
source share
2 answers

There are several ways to do this, but in my opinion, the best method is to use the 'PIMPL' idiom , which is quite common in C ++. Make the headers pure Objective-C and pure C ++ with pointers to an expired declaration structure containing the actual implementation. This is defined in the .mm file and then can use Objective-C ++.

In your example, you would do something like this:

 // Bh, pure Objective-C: struct BImpl; @interface B { struct BImpl* impl; } // ... // B.mm, mixed: #include "Ch" struct BImpl // since this is C++, it can actually have constructors/destructors { C* my_c; BImpl() : my_c(new C) {} ~BImpl() { delete my_c; my_c = NULL; } }; // make sure to alloc/initialise impl (using new) in B init* methods, // and free it (using delete) in the dealloc method. 

I really wrote an article about solving this particular problem, it may seem useful to you: http://philjordan.eu/article/strategies-for-using-c++-in-objective-c-projects - it also shows some other ways to solve it runtimes, including the original void* approach.

+15
source

As PMjordan writes in his blog article , BImpl in the @interface declaration needs a β€œstruct” key as follows.

 struct BImpl; @interface B { struct BImpl* impl; } 

I think he accidentally left this. If you need to include this header when you have many * .m files, this is of utmost importance. The added keyword 'struct' makes the Objective-C compiler understand this header as pure C for other .m files that import this header. Otherwise, other * .m files that import this header will not be compiled. This small solution saves you from changing * .m files to .mm files. Sometimes changing source .m files to .mm causes a lot of compilation errors.

+4
source

All Articles