gpt4 book ai didi

string - 如何将 UnsafePointer 转换为字符串?

转载 作者:行者123 更新时间:2023-11-28 05:34:04 24 4
gpt4 key购买 nike

我试过这个方法:

String.stringWithCString(cString: UnsafePointer<CChar>, encoding: NSStringEncoding)

但不幸的是,它只适用于 UnsafePointer<CChar> .我不知道如何转换 UnsafePointer<CUnsignedChar>UnsafePointer<CChar> .

最佳答案

struct UnsafePointer<T>有一个构造函数,它接受一个不同的不安全指针输入参数:

/// Convert from a UnsafePointer of a different type.
///
/// This is a fundamentally unsafe conversion.
init<U>(_ from: UnsafePointer<U>)

因此您可以从 ptr : UnsafePointer<CUnsignedChar> 创建一个字符串与

let str = String.stringWithCString(UnsafePointer(ptr), encoding: someEncoding)

或者,在 UTF-8 编码的情况下,更简单地使用

let str = String.fromCString(UnsafePointer(ptr))

注意泛型类型 <CChar>是从这里的上下文自动推断出来的,即最后一行相当于

let str = String.fromCString(UnsafePointer<CChar>(ptr))

关于string - 如何将 UnsafePointer<CUnsignedChar> 转换为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25850477/

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