我可以在编译和链接时将 C++ 主函数和类与 Objective-C 和/或 C 例程分开吗?

Can I separate C++ main function and classes from Objective-C and/or C routines at compile and link?(我可以在编译和链接时将 C++ 主函数和类与 Objective-C 和/或 C 例程分开吗?)

本文介绍了我可以在编译和链接时将 C++ 主函数和类与 Objective-C 和/或 C 例程分开吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小型 C++ 应用程序,我导入了 Objective-C 类.它作为 Objective-C++ 文件 .mm 工作,但任何包含可能最终包含一些 Objective-C 标头的标头的 C++ 文件都必须重命名为 .mm 扩展名,以用于正确的 GCC 驱动程序.

I have a small C++ application which I imported Objective-C classes. It works as Objective-C++ files, .mm, but any C++ file that includes a header which may end up including some Objective-C header must be renamed to a .mm extension for the proper GCC drivers.

有没有办法为 Objective-C 类编写纯 C++ 包装器,或者我可以以某种方式将 Objective-C 对象分离出来,然后单独链接它们?也许即使 Objective-C 类变成了一个小型库,我也可以在编译时静态重新链接?

Is there a way to write either a purely C++ wrapper for Objective-C classes or can I separate the Objective-C objects out somehow and just link them separately? Maybe even if the Objective-C classes became a small library I could statically re-link at compile time?

问题在于这段代码是跨平台的,在通常不使用 Objective-C 的系统(即不是 Mac)上编译起来更加困难.即使预处理器命令限制了任何在 Windows 或 Linux 上的 Objective-C 代码的实现,原始代码仍然具有 .mm 扩展名,并且 GCC 仍然将代码视为 Objective-C++.

The problem is that this code is cross-platform, and it is more difficult to compile on systems that normally do not use Objective-C (i.e. not Macs). Even though preprocessor commands restrict any implementation of Objective-C code on Windows or Linux, the original code still has .mm extensions and GCC still treats the code as Objective-C++.

推荐答案

通常你只需用 C++ 类包装你的 Objective-C 类,例如使用 不透明指针 并将对 C++ 方法的调用转发到 Objective-C 方法.

Usually you simply wrap your Objective-C classes with C++ classes by e.g. using opaque pointers and forwarding calls to C++ methods to Objective-C methods.

这样,您的可移植 C++ 源代码永远不必看到任何 Objective-C 包含的内容,理想情况下,您只需更换不同平台上包装器的实现文件.

That way your portable C++ sources never have to see any Objective-C includes and ideally you only have to swap out the implementation files for the wrappers on different platforms.

例子:

// c++ header:
class Wrapper {
    struct Opaque;
    Opaque* opaque;
    // ...
public:
    void f();
};

// Objective-C++ source on Mac:
struct Wrapper::Opaque {
    id contained;
    // ...
};

void Wrapper::f() {
    [opaque->contained f];
}

// ...

这篇关于我可以在编译和链接时将 C++ 主函数和类与 Objective-C 和/或 C 例程分开吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:我可以在编译和链接时将 C++ 主函数和类与 Objective-C 和/或 C 例程分开吗?

基础教程推荐