简体   繁体   中英

Calling C++ classes and methods within Objective-C

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM