简体   繁体   English

从目标C类调用C ++函数

[英]Calling C++ function from objective C class

我想从目标C类中调用c ++函数,但不确定如何调用。请提供一些示例代码或有用的链接来帮助我,谢谢

将Objective-C文件上的.m扩展名更改为.mm以使其成为Objective-C ++

An alternative to switching your class implementation file to Objective-C++ is to declare the C++ function as extern "C" , assuming its arguments are all C types. 将类实现文件切换到Objective-C ++的另一种方法是,将C ++函数声明为extern "C" ,假定其参数均为C类型。 Place that declaration inside a C-compatible C++ header file and include it from both the C++ file that implements the function and from the Objective-C file that calls it. 将该声明放在兼容C的C ++头文件中,并在实现该函数的C ++文件和调用它的Objective-C文件中都包括该声明。 This will of course only work if the data types of parameters and the return type are pure C types, but is in some cases "cleaner" than the Objective-C++ approach. 当然,这仅在参数的数据类型和返回类型为纯C类型的情况下才有效,但在某些情况下比Objective-C ++方法更“干净”。

Expanding on what pmjordan said, if you have a .m file calling in to a .mm or .cpp, make sure that the main header of the .mm or .cpp, where the functions you are calling are declared, have conditionally compiled extern "C" like this .h file: 扩展pmjordan所说的内容,如果您有一个.m文件调用.mm或.cpp,请确保已声明要调用函数的.mm或.cpp的主标头有条件地编译了extern "C"像.h这样的extern "C"文件:

#ifdef __cplusplus
extern "C" {
#endif

void functionA(void);
void functionB(const char *);

#ifdef __cplusplus
}
#endif

When this header is included as part of the .mm or .cpp, the extern "C" will do the right thing, and when the .h is compiled as part of the calling .c or .m file that calls those functions, the extern "c" is excluded and will not cause the compiler to complain. 当此标头作为.mm或.cpp的一部分包含在内时, extern "C"将做正确的事情,而当.h被编译为调用这些函数的.c或.m文件的一部分时, extern "c"被排除在外,不会引起编译器抱怨。

Using this solution will prevent you from needlessly changing .m files into .mm files just so you can simply call C routines in c++ files. 使用此解决方案将防止您不必要地将.m文件更改为.mm文件,以便仅在c ++文件中调用C例程。

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

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