gpt4 book ai didi

swift 3 : convert a null-terminated UnsafePointer to a string

转载 作者:搜寻专家 更新时间:2023-10-31 08:13:45 25 4
gpt4 key购买 nike

我有一个 c api,它返回一个空终止字符串,它是一个类型为 unsigned char* 的数组。 (对应于 UnsafePointer<UInt8> )。

Swift 有初始化器 String(validatingUTF8:) , 但参数必须是 UnsafePointer<CChar> (又名 UnsafePointer<Int8> ),并且没有简单的方法可以在两者之间进行转换。

如何将这个以 null 结尾的 C 字符串转换为 Swift 字符串?

最佳答案

在 Swift 3 中,String 有两个初始化器

public init(cString: UnsafePointer<CChar>)
public init(cString: UnsafePointer<UInt8>)

因此它可以从有符号和无符号字符的(空终止)序列创建。所以

let s = String(cString: yourCharPointer)

应该可以正常工作。


String 有另一个初始化器

public init?(validatingUTF8 cString: UnsafePointer<CChar>)

在错误格式的 UTF-8 序列上失败而不是替换它们通过替换字符。这个 init 方法没有对应的方法取无符号字符。

采用 CString.swift 中的现有实现作为示例,将其添加为扩展名并不难:

extension String {
public init?(validatingUTF8 cString: UnsafePointer<UInt8>) {
guard let (s, _) = String.decodeCString(cString, as: UTF8.self,
repairingInvalidCodeUnits: false) else {
return nil
}
self = s
}
}

然后

if let s = String(validatingUTF8: yourCharPointer) {
print(s)
} else {
print("invalid UTF-8")
}

也适用于有符号和无符号字符的(空终止)序列。

关于 swift 3 : convert a null-terminated UnsafePointer<UInt8> to a string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39533320/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com