我试图在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 ++方法吗?
谢谢!
答案 0 :(得分:2)
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