【问题标题】:Passing a file as a parameter to a C++ method from Swift从 Swift 将文件作为参数传递给 C++ 方法
【发布时间】:2018-03-14 16:05:36
【问题描述】:

我正在尝试在 Swift 应用程序中调用一些 C++ 代码。我没有编写 C++,也无法控制它。

我创建了一个 C++ 包装器来处理来自 Swift 的调用。我还在 C++ 文件中添加了一些测试函数,以验证我是从 Swift 调用 C++。这些函数只返回一个 int。

在C++头代码中有一个函数定义如下:

class GlobeProcessor {
public:
    void readFile(ifstream &inputFile);
    // ...
};

在我的包装器中,我定义了如下函数:

extern "C" void processGlobe(ifstream &file) {
    GlobeProcessor().readFile(file);
}

令人困惑的部分是如何在我的桥接头中引用它。目前桥接头包含以下内容:

// test function
int getNumber(int num);

void processGlobeFile(ifstream &file);

测试函数成功,所以我可以从 Swift 访问 C++。但是,将processGlobeFile 的声明添加到桥接头会产生以下编译错误:

Unknown type name 'ifstream'

我尝试将适当的导入添加到桥接头中,但没有成功。我不是一个经验丰富的 C++ 人,所以我真的不知道我是否以正确的方式处理这个问题。有人可以帮我理解如何将文件作为参数从 Swift 传递给 C++ 方法吗?

谢谢!

【问题讨论】:

    标签: c++ ios swift bridging-header


    【解决方案1】:

    Swift 无法导入 C++。 ifstream 是 C++ 类,参数也是 C++ 引用。这些都不适用于 Swift。

    您必须编写一个 C 函数来包装您的 C++ 调用并将您的 ifstream 对象视为不透明的引用。

    您的包装函数也必须声明 extern "C" 不只是这样定义,否则包含标头的其他 C++ 文件将假定它具有名称修饰。

    这样的东西可能会起作用,但我根本没有测试过:

    // header
    #if !defined _cplusplus
    
    typedef struct ifstream ifstream; // incomplete struct def for C opaque type
    
    #else
    
    extern "C" {
    
    #endif
    
    int getNumber(int num);
    
    void processGlobeFile(ifstream *file); // note you need to use a pointer not a reference
    
    #if defined __cplusplus
    
    } // of the exten C
    
    #endif
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-13
      • 2015-02-12
      • 2021-02-05
      • 2018-12-11
      • 1970-01-01
      • 2013-02-08
      • 2018-09-09
      • 1970-01-01
      相关资源
      最近更新 更多