如何将 Swift 字符串数组传递给采用 char ** 参数的 C 函数 [英] How to pass an array of Swift strings to a C function taking a char ** parameter

查看:26
本文介绍了如何将 Swift 字符串数组传递给采用 char ** 参数的 C 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试与来自 Swift 的旧 C 终端应用程序进行交互.我已经成功地集成了源代码并将头文件从 C 桥接到 Swift.代码从 Xcode 6.3 beta 编译并运行.我已将终端应用程序的主要入口点重命名为:

I'm trying to interact with an old C terminal app from Swift. I've successfully integrated the source code and bridged the headers from C to Swift. The code compiles and runs from Xcode 6.3 beta. I've renamed the terminal app's main entry point to:

int initialize(int argc, char **argv);

尽管如此,我正在努力将参数从 Swift 传递给这个 C 函数.我的挑战是以正确的格式转换参数.来自 Swift 的典型输入如下所示:

Nevertheless, I'm struggling to pass the arguments from Swift to this C function. My challenge is to convert the arguments in the right format. Typical input from Swift would look like:

let args = ["-c", "1.2.3.4", "-p", "8000"]

我试过弄乱cStringUsingEncoding(NSUTF8StringEncoding)"和withUnsafePointer",但到目前为止没有运气.非常感谢任何帮助!

I've tried messing with "cStringUsingEncoding(NSUTF8StringEncoding)" and "withUnsafePointer", but no luck so far. Any help is greatly appreciated!

推荐答案

C 函数

int initialize(int argc, char **argv);

映射到 Swift 为

is mapped to Swift as

func initialize(argc: Int32, argv: UnsafeMutablePointer<UnsafeMutablePointer<Int8>>) -> Int32

这是一个可能的解决方案:

This is a possible solution:

let args = ["-c", "1.2.3.4", "-p", "8000"]

// Create [UnsafeMutablePointer<Int8>]:
var cargs = args.map { strdup($0) }
// Call C function:
let result = initialize(Int32(args.count), &cargs)
// Free the duplicated strings:
for ptr in cargs { free(ptr) }

它使用了strdup($0)中的事实Swift 字符串 $0 会自动转换为 C 字符串,如 String value to UnsafePointer 中所述函数参数行为.

It uses the fact that in strdup($0) the Swift string $0 is automatically converted to a C string, as explained in String value to UnsafePointer<UInt8> function parameter behavior.

这篇关于如何将 Swift 字符串数组传递给采用 char ** 参数的 C 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆