我想从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)
来转换它。如果我打印ln(buf[0]),它将打印一个整数67,这是'C'的ascii值,我如何将ln(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/