c++ - 如何将两个字符串从 Swift 传递到 C++ 函数,并获取整数数组?

标签 c++ macos swift

我正在尝试将两个字符串从 Swift 传递到 C++ 函数,在那里处理它们,然后返回一个整数数组(可能是一个 vector ),但还不确定。

我已经尝试过(C++ 函数声明):

void exmaple(char* one, char* two);

但无法将字符串从 Swift 传递到 C++。

然后我稍微改变了函数:

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

    cout<<"String b is: "<<b<<endl;
}

并尝试在 Swift 中调用该函数:

let aStr = UnsafeMutablePointer<String>.alloc(10)
aStr.initialize("stringA")

let bStr = UnsafeMutablePointer<String>.alloc(10)
bStr.initialize("stringB")

example(aStr, bStr)

但我得到的唯一输出是:

String b is: 

如何将两个字符串从 Swift 传递到 C++ 函数,然后返回整数数组/vector ?

最佳答案

Swift 有一些神奇的桥接功能,允许您将常规 Swift 字符串直接传递到 C 函数中。例如,strlen有签名size_t strlen(const char *) ,在 Swift 中为 func strlen(_: UnsafePointer<Int8>) -> UInt但你可以用普通字符串来调用它,如下所示:

import Darwin

let greeting: String = "Hello!"

strlen(greeting)   // returns 6

strlen("Goodbye")  // returns 7

编译器将自动为调用生成以 null 结尾的 C 字符串。

不幸的是,你问题的最后部分要棘手得多。实际上不仅没有到 C++ 的桥接,只有 C 和 Objective-C,而且绝对没有能力传回 C++ vector 。你最好的选择是要么通过 Objective-C 层并传回 NSArray ,或者使用 C 风格传递空缓冲区并让函数将值写入其中。

关于c++ - 如何将两个字符串从 Swift 传递到 C++ 函数,并获取整数数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29546071/

相关文章:

c++ - 将 CString 转换为 unsigned long

c++ - 升级我的 mac 后编译 mpic++ 不再有效

ios - 半透明,带有快速导航栏

python - osx sierra 没有名为 pip 的模块

ruby - IRB 历史不适用于 Ruby 2.3.0

ios - 在 swift 4 中使用带有货币格式化程序的负数

ios - 更新 Xcode 后,我的 Swift 3 项目运行不正确但构建成功

c++ - 使用 sprintf 打印十六进制值的便携方式

c++ - 为什么 (1+3)[a] 和 a[1+3] 一样?

c++ - 为什么return()时返回值优化不起作用