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

查看:456
本文介绍了如何将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,

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字符串, 如 UnsafePointer< UInt8>中的字符串值所述函数参数行为.

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天全站免登陆