Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mixing C++ and Objective C

Where can i find a concrete document or a dos and donts documentation on using C++ with Objective-C?

Apple seems to have removed that document from their website and i am all puzzled with collating bits of information from blogs and questions posted here.

Anyone can guide about the same.

When do we use .mm file, while mixing syntax or while using an object in .m file which belongs to a C++ class ?

While passing objects between functions belonging to two different language like passing objective-c object to a function in cpp file is it necessary to collect it in void * or can I use (ObjectiveC inteface)*?

like image 832
tusharfloyd Avatar asked Mar 28 '12 14:03

tusharfloyd


1 Answers

You need to use Objective-C++ whenever you are either #include/#importing or directly writing both Objective-C and C++ code in the same file. It's usually obvious with explicit code; the #includes are often less so, and you need to take care to avoid "leaking" one of the languages into too much of the other. Your example of #importing a C++ header file is clear-cut: you can only do that with Objective-C++. Note that if your Cplusplus was a struct type, you could forward-declare it as such instead of #importing a C++ header.

If you do this in a header, it will "poison" the header to only work in that mode. You'll need to actively avoid this, or your whole project will soon end up with only .mm files. I have documented some techniques in this article and previously, in this earlier article. For newer versions of Objective-C, you can also add ivars to classes in category extensions. This means you can define C++-typed ivars in your .mm file, not the header, which allows .m files to #import it.

For your second question (Please only ask one question at a time): the id type is defined in the objc.h header file in terms of C and thus will work in both Objective-C and C++. Likewise, the Objective-C runtime API is exposed in terms of C functions, which will work from C++, too. If you actually want to send messages and access properties on Objective-C objects with the canonical syntax from C++ code, you'll need to switch that file to Objective-C++.

like image 189
pmdj Avatar answered Oct 15 '22 02:10

pmdj