Swift 3:转换以 null 结尾的 UnsafePointer<UInt8>到一个字符串 [英] Swift 3: convert a null-terminated UnsafePointer<UInt8> to a string

查看:26
本文介绍了Swift 3:转换以 null 结尾的 UnsafePointer<UInt8>到一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ac api,它返回一个空终止的字符串,它是一个 unsigned char* 类型的数组(对应于 UnsafePointer).

I have a c api that returns a null terminated string that is an array of type unsigned char* (which would correspond to UnsafePointer<UInt8>).

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

Swift has the initializer String(validatingUTF8:), but the argument has to be UnsafePointer<CChar> (a.k.a. UnsafePointer<Int8>), and there is no trivial way to convert between the two.

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

How do I convert from this null-terminated c-string to a Swift string?

推荐答案

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

In Swift 3, String has two initializers

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

因此它可以从有符号和无符号字符的(以空字符结尾的)序列创建.所以

therefore it can be created from (null-terminated) sequences of both signed and unsigned characters. So

let s = String(cString: yourCharPointer)

应该可以正常工作.

String 有另一个初始化器

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

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

which fails on ill-formed UTF-8 sequences instead of replacing them by the replacement characters. This init method has no counterpart taking unsigned characters.

采用 CString.swift 作为例子,添加这个作为扩展并不太难:

Taking the existing implementations in CString.swift as examples, it is not too difficult to add this as an extension:

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")
}

也适用于有符号和无符号字符的(以空字符结尾的)序列.

also works with (null-terminated) sequences of both signed and unsigned characters.

这篇关于Swift 3:转换以 null 结尾的 UnsafePointer&lt;UInt8&gt;到一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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