呼叫 C++目标 C 类的函数
我想从我的目标 C 类中调用一个 C++ 函数,我不知道如何调用它。请有人通过提供一些示例代码或有用的链接来帮助我 提前致谢
I want to call a c++ function from my objective C class i am not sure how to call it.Please somebody help me by giving some sample codes or useful links
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将 Objective-C 文件上的
.m
扩展名更改为.mm
,使其成为 Objective-C++。Change the
.m
extension to.mm
on the Objective-C file to make it Objective-C++.将类实现文件切换到 Objective-C++ 的另一种方法是将 C++ 函数声明为
extern "C"
,假设其参数都是 C 类型。将该声明放入与 C 兼容的 C++ 头文件中,并从实现该函数的 C++ 文件和调用该函数的 Objective-C 文件中包含该声明。当然,只有参数的数据类型和返回类型是纯 C 类型时,这才有效,但在某些情况下比 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. 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. 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.扩展 pmjordan 所说的内容,如果您有一个 .m 文件调用 .mm 或 .cpp,请确保 .mm 或 .cpp 的主标头(您调用的函数在其中声明)已进行条件编译 < code>extern "C" 像这样的 .h 文件:
当此标头作为 .mm 或 .cpp 的一部分包含时,
extern "C"
将执行正确的操作,并且当.h 被编译为调用这些函数的调用 .c 或 .m 文件的一部分,extern "c"
被排除,不会导致编译器抱怨。使用此解决方案将防止您不必要地将 .m 文件更改为 .mm 文件,以便您可以简单地在 C++ 文件中调用 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: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, theextern "c"
is excluded and will not cause the compiler to complain.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.