将Swift字符串数组转换为C字符串数组指针 [英] Convert a Swift Array of String to a to a C string array pointer

查看:441
本文介绍了将Swift字符串数组转换为C字符串数组指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Swift 3,我需要与C API进行交互,例如,C API接受以NULL终止的字符串列表.

I'm on Swift 3, and I need to interact with an C API, which accepts a NULL-terminated list of strings, for example

const char *cmd[] = {"name1", "value1", NULL};
command(cmd);

在Swift中,API的导入方式如下

In Swift, the API was imported like

func command(_ args: UnsafeMutablePointer<UnsafePointer<Int8>?>!)

使用类型转换或unsafeAddress(of:)尝试了数百次后,我仍然无法完成这项工作.即使我传递通过编译的有效指针,它也会在运行时崩溃,提示无效的内存访问(在strlen函数处).也许是关于ARC的事情?

After trying hundreds of times using type casting or unsafeAddress(of:) I still cannot get this work. Even though I pass a valid pointer that passed compilation, it crashes at runtime saying invalid memory access (at strlen function). Or maybe it's something about ARC?

let array = ["name1", "value1", nil]

// ???
// args: UnsafeMutablePointer<UnsafePointer<Int8>?>

command(args)

推荐答案

您可以按照与

You can proceed similarly as in How to pass an array of Swift strings to a C function taking a char ** parameter. It is a bit different because of the different const-ness of the argument array, and because there is a terminating nil (which must not be passed to strdup()).

这是应该如何工作的:

let array: [String?] = ["name1", "name2", nil]

// Create [UnsafePointer<Int8>]:
var cargs = array.map { $0.flatMap { UnsafePointer<Int8>(strdup($0)) } }
// Call C function:
let result = command(&cargs)
// Free the duplicated strings:
for ptr in cargs { free(UnsafeMutablePointer(mutating: ptr)) }

这篇关于将Swift字符串数组转换为C字符串数组指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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