我尝试过这种方法:
String.stringWithCString(cString: UnsafePointer<CChar>, encoding: NSStringEncoding)
但不幸的是,它只适用于UnsafePointer<CChar>
。我不知道如何将UnsafePointer<CUnsignedChar>
转换为UnsafePointer<CChar>
。
答案 0 :(得分:2)
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))
答案 1 :(得分:0)
从 Swift 3.0 开始
let str = String(cString: UnsafePointer<CChar>(ptr))