我想要一个 wchar_t
来自 C
的数组库,并将其转换为 swift 数据结构,我的代码在这里:
func getResults(recognizer: UnsafeMutablePointer<Void>, stroke: UnsafeMutablePointer<Int32>, touchState: Int32) -> [String] {
var bufLen : Int32
var buf = UnsafeMutablePointer<wchar_t>.alloc(Int(bufLen))
getRecognition(recognizer, stroke, touchState, buf, bufLen)
var results = String.fromCString(buf)! //this line has an error, cause the buf is wchar_t*, not char*
}
如何将 buf 转换为 swift 数据结构?
我知道 buf 是不是 UnsafeMutablePointer<Int8>.alloc(Int(bufLen))
, 我们可以使用 String.fromCString(buf)
!进行转换。
如果我 println(buf[0]),它会打印一个整数 67,它是 'C' 的 ascii 值,我如何将 println(buf[0]) 打印为 'C' 而不是 0? 谢谢!
最佳答案
wchar_t
是 Int32
的别名,包含一个 UTF-32 代码点
按主机字节顺序(在所有当前的 iOS 和 OS X 上都是小端
平台)。
因此您可以将缓冲区转换为 Swift 字符串,如下所示:
if let str = NSString(bytes: UnsafePointer(buf),
length: wcslen(buf) * sizeof(wchar_t),
encoding: NSUTF32LittleEndianStringEncoding) as? String {
println(str)
} else {
// encoding problem ...
}
(假设来自 C 库函数的 wchar_t
字符串
以零结尾。)
关于c - 如何快速将 wchar_t 转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31043593/