简体   繁体   English

在Objective-C中调用C ++类和方法

[英]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++. 我正在开发一个iOS应用程序,其中大部分后端已经在C ++中完成。 The interface is obviously in Obj-C and I'm not sure how to use the two languages at the same time together. 界面显然是在Obj-C中,我不知道如何同时使用这两种语言。

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: 基本上,我希望在Objective-C文件中有一个Song数据库,而不是对该歌曲数据库/对象执行这些操作:

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? 显然这是所有C ++但我如何在Objective-C文件中执行此操作?

Make a file with .mm extension and the compiler will treat it is an Objective-C++ source code. 创建一个扩展名为.mm的文件,编译器会认为它是一个Objective-C ++源代码。 This would allow you to mix the C++ and Objective-C code. 这将允许您混合使用C ++和Objective-C代码。

Basically, you can call C++ functions and declare the variables which have the C++ class type. 基本上,您可以调用C ++函数并声明具有C ++类类型的变量。

In the .mm file you should include the .h files for your C++ code and then use the C++'s declarations in Objective-C. 在.mm文件中,您应该包含C ++代码的.h文件,然后在Objective-C中使用C ++的声明。

One sufficient restriction: you cannot inherit C++ classes from Objective-C interfaces and vice versa. 一个足够的限制:您不能从Objective-C接口继承C ++类,反之亦然。

Of course, the "best" part is the need for manual memory management for C++ objects (see rickster's comment). 当然,“最佳”部分是需要对C ++对象进行手动内存管理(请参阅rickster的评论)。 There is not automatic garbage collection, so when you declare pointers and allocate some memory you've got to deallocate them later. 没有自动垃圾收集,所以当你声明指针并分配一些内存时,你必须在以后释放它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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