我想为 iOS 和 Android 原生创建一个应用程序(我过去使用过 Xamarin,我不想再使用它了),所以我的下一个选择是用 C++ 编写共享代码,这可以是在两个平台上本地编译。
现在我想知道是否可以直接在 Swift 中使用 C++。我发现的唯一解决方案建议在 Objective-C++ 中创建一个包装器并通过桥接 header 公开它,但我不希望这种开销。
这是为 Swift 计划的吗?或者是否有其他解决方案可以跳过 Objective-C++ 步骤?
最佳答案
目前不支持。只有两种方法可以从 Swift 代码与 C++ 代码对话:
正如您已经发现的那样,使用 Objective-C++ 将您的 C++ 代码包装在 ObjC 中。
利用 C++ 大部分与 C 兼容这一事实,Swift 可以调用 C,并围绕 C++ 类编写 C 包装器,然后从 Swift 中使用它。一种常见的方法是:
cppwrapper.h
struct MyCppClass; // In C++ class and struct are the same, so this looks like a C struct to C, and as long as you don't look inside it, you can use pointers to it in C code.
extern "C" { // Tell C++ to turn off overloading based on type so it's C-compatible.
struct MyCppClass* MyCppClass_new( int firstParam );
void MyCppClass_delete( struct MyCppClass* inThis );
void MyCppClass_setFirstParam( struct MyCppClass* inThis, int firstParam );
} // extern "C"
cpp包装器.cpp
#include "cppwrapper.h"
#include "MyCppClass.hpp"
extern "C" MyCppClass* MyCppClass_new( int firstParam )
{
return new MyCppClass( firstParam );
}
extern "C" void MyCppClass_delete( MyCppClass* inThis )
{
delete inThis;
}
extern "C" void MyCppClass_setFirstParam( struct MyCppClass* inThis, int firstParam )
{
inThis->SetFirstParam( firstParam );
}
您甚至可以定义一个 MyCppClassSwiftWrapper
,它有一个 COpaquePointer 类型的实例变量,您可以在其中存储 C++ 对象。此类将在其构造函数中调用 MyCppClass_new
,在其析构函数中调用 MyCppClass_delete
,并将包含一个围绕 MyCppClass_setFirstParam
的包装器,该包装器使用 COpaquePointer 作为 >inThis
参数放入其中。
我曾经写过一个(非常原始的)实用程序,它可以让你标记 C++ header 并自动为它们生成简单的 C 和 Swift 包装器(https://github.com/uliwitness/cpptoswift/),但它不适用于模板,你可能必须添加更多类型映射到它。它还不能正确处理传递/返回 C++ 对象。
还有 https://github.com/sandym/swiftpp/这一切都做得更好,但我认为它仍然使用 Objective-C 作为其包装器,但至少你不必自己编写。
关于c++ - 我可以直接从 Swift 使用 C++ 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43209439/