有什么办法可以调用 c++没有 .mm 扩展名的 Objective-C 代码中的函数?
有没有办法从 Objective-C 代码调用 C++ 函数而不需要 .mm 扩展名? 例如,也许可以创建一个 C 包装器或其他任何可以在这种情况下提供帮助的东西? 我知道可以为 .m 文件分配类型“objective-c++ source”,但这不是我想要的。
Is there any way to call c++ functions from objective-c code without .mm extension?
For example maybe it is possible to create a C wrapper or anything else that can help in this situation?
I know that it is possible assign type "objective-c++ source" for .m files but it is not what I want.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,我经常这样做。您将需要少量
.mm
粘合代码,但您使用包装器的直觉是正确的。您可能对包装 C++ - 练习 2 感兴趣。有充分的理由避免过度使用 .mm 文件。根据我的经验,它们编译速度较慢,运行速度较慢(特别是在 ARC 下,它们会产生大量开销),使 gdb 感到困惑,并且 ObjC 和 C++ 类的混合非常混乱且容易出错。在 ObjC 和 C++ 之间用薄层进行分割是一个好方法。
Yes, I do this often. You will need a small amount of
.mm
glue code, but your intuition of using wrappers is correct. You may be interested in Wrapping C++ - Take 2.There are good reasons to avoid excessive use of .mm files. They compile slower, run slower (particularly under ARC where they incur significant overhead), confuse gdb in my experience, and the mixing of ObjC and C++ classes is quite confusing and error-prone. Segmenting your ObjC and C++ with a thin layer between them is a good approach.
使用 Objective-C++ 是更简单的方法,但如果由于某种原因你不能使用它*,你可以使用 C 包装器,但它必须是纯 C 的。所以它看起来像这样
:
impl*
函数可能不是必需的,我已经有一段时间没有做过这样的事情了。使用此方法,您可以将MyClassWrap.h
包含在 Objective-C 文件中,并间接访问 C++ 函数,而无需将文件编译为 Objective-C++。*也许代码中有太多名为 class 的变量,您无法更改
Using Objective-C++ is the eaiser way to go, but if for some reason you can't use it* you can go through a C wrapper, but it has to be purely C. So it will look something like this:
Having the separate
impl*
functions might not be necessary, it's been a while since I've done something like this. With this appoach, you can includeMyClassWrap.h
in an Objective-C file and indirectly get access to C++ functions with no files compiled as Objective-C++.*Maybe too many variables named class in code you can't change