将C字符串数组转换为Swift字符串数组 [英] Converting array of C strings to Swift string array

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

问题描述

在Swift 3中,签名为const char *f()的C函数在导入时被映射为UnsafePointer<Int8>! f().结果可以转换为Swift字符串,如下所示:

In Swift 3, C function with signature const char *f() is mapped to UnsafePointer<Int8>! f() on import. It's result can be converted to a Swift string as:

let swiftString = String(cString: f())

问题是,如何将以NULL结尾的C字符串C数组映射到Swift字符串数组?

The question is, how a NULL terminated C array of C strings can be mapped to Swift array of strings?

原始的C签名:

const char **f()

导入的Swift签名:

Imported Swift signature:

UnsafeMutablePointer<UnsafePointer<Int8>?>! f()

快速字符串数组:

let stringArray: [String] = ???

推荐答案

据我所知,没有内置方法. 您必须遍历返回的指针数组,将C字符串转换为Swift String,直到找到nil指针:

There is no built-in method as far as I know. You have to iterate over the returned pointer array, converting C strings to Swift Strings, until a nil pointer is found:

if var ptr = f() {
    var strings: [String] = []
    while let s = ptr.pointee {
        strings.append(String(cString: s))
        ptr += 1
    }
    // Now p.pointee == nil.

    print(strings)
}


备注: Swift 3使用可选的指针作为可以为nil的指针. 在您的情况下,f()返回一个隐式展开的可选内容,因为 头文件未经过审核":编译器不知道是否 该函数是否可以返回NULL.


Remark: Swift 3 uses optional pointers for pointers that can be nil. In your case, f() returns an implicitly unwrapped optional because the header file is not "audited": The compiler does not know whether the function can return NULL or not.

使用可空性注释"可以提供该信息 到Swift编译器:

Using the "nullability annotations" you can provide that information to the Swift compiler:

const char * _Nullable * _Nullable f(void);
// Imported to Swift  as
public func f() -> UnsafeMutablePointer<UnsafePointer<Int8>?>?

如果函数可以返回NULL

const char * _Nullable * _Nonnull f(void);
// Imported to Swift  as
public func f() -> UnsafeMutablePointer<UnsafePointer<Int8>?>

如果保证f()返回非NULL结果.

if f() is guaranteed to return a non-NULL result.

有关可空性注释的更多信息,请参见例如 在Swift博客中可空性和Objective-C .

For more information about the nullability annotations, see for example Nullability and Objective-C in the Swift blog.

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

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