我可以直接从Swift使用C ++吗?

时间:2017-04-04 14:00:20

标签: c++ ios swift objective-c++

我想为iOS和Android本机创建一个应用程序(过去我曾经使用过Xamarin,我不想再使用它了),所以我的下一个选择是用C ++编写共享代码,这可以是本地在两个平台上编译。

现在我想知道我是否可以直接从Swift使用C ++。我发现的唯一解决方案建议在Objective-C ++中创建一个包装器并通过桥接头公开它,但我不想要这个开销。

这是为Swift计划的吗?或者是否有其他解决方案可以跳过Objective-C ++步骤?

3 个答案:

答案 0 :(得分:2)

目前不支持。与Swift代码中的C ++代码交谈只有两种方法:

  1. 使用Objective-C ++将您的C ++代码包装在ObjC中,如您所见。

  2. 利用C ++主要与C兼容的事实,Swift可以调用C,并在C ++类中编写C包装,并使用Swift中的C包。一种常见的方法是:

  3. 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"
    

    cppwrapper.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 ++标题并自动为它们生成简单的C和Swift包装器(https://github.com/uliwitness/cpptoswift/),但是它不能使用模板而你&#39 ; ll可能需要添加更多类型映射。它还没有正确处理传递/返回C ++对象。

    还有https://github.com/sandym/swiftpp/做得更好,但我认为它仍然使用Objective-C作为其包装,但至少你不必自己写它

答案 1 :(得分:0)

如果在Bridging-Header.h中将C ++标题包含为C兼容,则可以在swift项目中无缝使用它。

#ifndef Bridging_Header_h
#define Bridging_Header_h

#import <Foundation/Foundation.h>
#include "CPlusPlusHeader.h"


#endif /* Bridging_Header_h */

答案 2 :(得分:0)

我创建了一个Objective-C ++框架,该框架有助于简化这种桥接:CXXProxyKit。请看看!