在 Swift 3 中,带有签名的 C 函数const char *f()
被映射到UnsafePointer<Int8>! f()
关于进口。它的结果可以转换为 Swift 字符串,如下所示:
let swiftString = String(cString: f())
问题是,如何将 NULL 终止的 C 字符串数组映射到 Swift 字符串数组?
原始C签名:
const char **f()
导入的 Swift 签名:
UnsafeMutablePointer<UnsafePointer<Int8>?>! f()
Swift 字符串数组:
let stringArray: [String] = ???
据我所知,没有内置方法。
您必须迭代返回的指针数组,将 C 字符串转换为 SwiftString
s,直到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 使用可选指针作为指针,可以nil
。
就你而言,f()
返回一个隐式解包的可选值,因为
头文件未经“审核”:编译器不知道是否
该函数可以返回NULL
or not.
使用“可空性注释”,您可以提供该信息
到 Swift 编译器:
const char * _Nullable * _Nullable f(void);
// Imported to Swift as
public func f() -> UnsafeMutablePointer<UnsafePointer<Int8>?>?
如果函数可以返回NULL
, and
const char * _Nullable * _Nonnull f(void);
// Imported to Swift as
public func f() -> UnsafeMutablePointer<UnsafePointer<Int8>?>
if f()
保证返回非 NULL 结果。
有关可空性注释的更多信息,请参见示例可空性和 Objective-C https://developer.apple.com/swift/blog/?id=25在 Swift 博客中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)