我试过这种方法:
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>转换为String?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25850477/