【问题标题】:How to define string parameters in C++ header file - Bridged with Swift?如何在 C++ 头文件中定义字符串参数 - 与 Swift 桥接?
【发布时间】: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::arraystd::vector。如果您想要推送/弹出/调整大小/清除/等数组,或者如果它有很多数据使用 std::vector,如果它是硬编码长度并且非常少量的数据使用 std::array。

标签: c++ xcode string macos swift


【解决方案1】:

您不能在 extern "C" 声明中使用类类型。您可以引入以下技巧:

标题:

#if __cplusplus
extern "C" {
#endif

int* example(void *one, void *two);

#ifdef __cplusplus
}
#endif

来源:(假定为.cpp)

#include <string>
using namespace std;
extern "C" {

    int* example(void *one, void *two)
    {
        string &a = *reinterpret_cast<string*>(one);
        string &b = *reinterpret_cast<string*>(two);
    ...
    }
}

您必须通过 ptr 传递字符串。

【讨论】:

  • 我尝试使用以下方式传递字符串: let aStr = UnsafeMutablePointer.alloc(1) aStr.initialize(str) ,但 C++ 中的字符串为空(没有崩溃或错误)跨度>
  • 很抱歉,我不会快速处理。你可以转换一个文字字符串进行测试吗?
  • 好的,我得到了字符串。我怎样才能返回一个整数向量?由于矢量类型,我再次在标题中收到该错误...
  • 您可以使用相同的策略传递指针的地址作为参数 (int * * pptr) 然后,您可以用数组的地址填充指针: *pptr = (int * ) malloc(值);
猜你喜欢
  • 1970-01-01
  • 2017-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-04
  • 2016-03-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多