【发布时间】:2015-04-09 17:43:28
【问题描述】:
我有一个使用 Swift 和 C++(带有桥接头)的 Xcode 项目,我正在尝试用 2 个字符串参数在 C++ 中创建一个函数,并将整数数组返回给 Swift:
.cpp 文件:
int* example(string one, string two)
{
int test[3] = {7,2,3};
return test;
}
.h 文件:
#if __cplusplus
extern "C" {
#endif
int* example(string one, string two); //ERROR HERE
#ifdef __cplusplus
}
#endif
我收到此错误(在 .h 文件中):
未知类型名称“字符串”
我试图将字符串头文件包含到标题中,但随后出现错误(我还必须在string 之前添加std::):
新函数声明:
int* example(std::string one, std::string two);
错误(在第一个std::)
预期的')'
我真的在这里失去了耐心,我做错了什么?
【问题讨论】:
-
为什么在
extern "C"中有它?如果您使用#include <string>,int* example(std::string one, std::string two);没有任何问题,但是您正在返回一个指向数组的指针,该数组在返回后将不存在。您也可能不想按值获取这些字符串 - 按值阅读与引用与指针 -
由于 Swift - youtube.com/watch?v=0x6JbiphNS4 ,我在 extern "C" 中有它,没有它就无法工作。无论如何,我应该如何返回一个 int 数组?
-
您可以使用
std::array或std::vector。如果您想要推送/弹出/调整大小/清除/等数组,或者如果它有很多数据使用 std::vector,如果它是硬编码长度并且非常少量的数据使用 std::array。
标签: c++ xcode string macos swift