我可以在编译和链接时从Objective-C和/或C例程中分离C ++主函数和类吗? [英] Can I separate C++ main function and classes from Objective-C and/or C routines at compile and link?
问题描述
我有一个小C ++应用程序,我导入Objective-C类。它工作作为Objective-C + +文件,.mm,但任何包含一个标题,可能最终包括一些Objective-C头文件的C ++文件必须重命名为适当的GCC驱动程序的.mm扩展名。
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];
}
// ...
这篇关于我可以在编译和链接时从Objective-C和/或C例程中分离C ++主函数和类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!