将C字符串数组转换为Swift字符串数组

Zme*_*mey 6 arrays pointers type-conversion swift swift3

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

let swiftString = String(cString: f())
Run Code Online (Sandbox Code Playgroud)

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

原始C签名:

const char **f()
Run Code Online (Sandbox Code Playgroud)

导入的Swift签名:

UnsafeMutablePointer<UnsafePointer<Int8>?>! f()
Run Code Online (Sandbox Code Playgroud)

Swift数组字符串:

let stringArray: [String] = ???
Run Code Online (Sandbox Code Playgroud)

Mar*_*n R 11

据我所知,没有内置方法.你必须迭代返回的指针数组,将C字符串转换为Swift Strings,直到nil找到一个指针:

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)
}
Run Code Online (Sandbox Code Playgroud)

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

使用"nullability annotations",您可以将该信息提供给Swift编译器:

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

如果函数可以返回NULL,和

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

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

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