简体   繁体   English

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

[英]Converting array of C strings to Swift string array

In Swift 3, C function with signature const char *f() is mapped to UnsafePointer<Int8>! f() 在Swift 3中,带有签名const char *f() C函数被映射到UnsafePointer<Int8>! f() UnsafePointer<Int8>! f() on import. UnsafePointer<Int8>! f()关于进口。 It's result can be converted to a Swift string as: 它的结果可以转换为Swift字符串:

let swiftString = String(cString: f())

The question is, how a NULL terminated C array of C strings can be mapped to Swift array of strings? 问题是,如何将NULL终止的C字符串C字符串映射到Swift字符串数组?

The original C signature: 原始C签名:

const char **f()

Imported Swift signature: 导入的Swift签名:

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

Swift array of strings: Swift数组字符串:

let stringArray: [String] = ???

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 String s, until a nil pointer is found: 你必须遍历返回的指针数组,将C字符串转换为Swift String ,直到找到一个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)
}

Remark: Swift 3 uses optional pointers for pointers that can be nil . 备注: Swift 3使用可选指针作为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. 在您的情况下, f()返回一个隐式解包的可选项,因为头文件未被“审计”:编译器不知道该函数是否可以返回NULL

Using the "nullability annotations" you can provide that information to the Swift compiler: 使用“nullability annotations”,您可以将该信息提供给Swift编译器:

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

if the function can return NULL , and 如果函数可以返回NULL ,和

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

if f() is guaranteed to return a non-NULL result. 如果f()保证返回非NULL结果。

For more information about the nullability annotations, see for example Nullability and Objective-C in the Swift blog. 有关可空性注释的更多信息,请参阅Swift博客中的Nullability和Objective-C

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM