c - 如何快速将 wchar_t 转换为字符串

标签 c swift

我想要一个 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_tInt32 的别名,包含一个 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/

相关文章:

c - C中的一种自修改程序

python - 从 C Visual Studio 调用 open cv python 代码进行图像显示

ios - 如何在函数内返回 UIImage?

ios - Swift、iOS15、UIKit、CollectionView header 问题

ios - 如何检测 Swift 4 中计划通知何时被触发

ios - 从点数组中获取 UIImage

c++ - "[Error] pointer value used where a floating point value was expected"如何解决此错误?

c - 使用 Linux C 通过 SOCKS5 进行 HTTP 请求

c - 如何删除所有可能的二叉树节点?

iOS - AudioKit 在接听电话时崩溃