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

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

问题描述

我使用的是 Swift 3,我需要与 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)

推荐答案

您可以像在 如何将 Swift 字符串数组传递给采用 char ** 参数的 C 函数.因为不同所以有点不同const - 参数数组的性质,并且因为有一个终止nil(不得传递给 strdup()).

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