1

I'm working on an iOS application where most of the backend has already been done in C++. The interface is obviously in Obj-C and I'm not sure how to use the two languages at the same time together.

Basically, I want to have a Song datamember in my Objective-C file and than perform these kind of actions to that song datamember/object:

Song song("Hardcore Beatzzz", "RockzStarsz", 60);
song.setTimeSig(4,4);

Track synthTrack;
synthTrack.setTrackName("sinussynth #1");

Note note3(880, 100, 8, 1, 17);
synthTrack.addNote(note3);

playlist.addTrack(synthTrack);

So obviously this is all C++ but how would I do this within my Objective-C files?

1 Answer 1

4

Make a file with .mm extension and the compiler will treat it is an Objective-C++ source code. This would allow you to mix the C++ and Objective-C code.

Basically, you can call C++ functions and declare the variables which have the C++ class type.

In the .mm file you should include the .h files for your C++ code and then use the C++'s declarations in Objective-C.

One sufficient restriction: you cannot inherit C++ classes from Objective-C interfaces and vice versa.

Of course, the "best" part is the need for manual memory management for C++ objects (see rickster's comment). There is not automatic garbage collection, so when you declare pointers and allocate some memory you've got to deallocate them later.

Sign up to request clarification or add additional context in comments.

3 Comments

I should have mentioned I know about the .mm extension. But does that mean I can just mix the sytax with each other? And what about using a C++ object as an Objective-C datamember?
I've added a point: you can't derive ObjC interfaces from C++ classes. Thats the only limitation. A pointer to C++ class as a property in ObjC interface is a valid construction.
Yes, you can make a C++ object an ivar in an Objective-C class. You'll have to be sure to take care of its memory, calling destructor at appropriate times, etc. Apple's docs have more info.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.