【问题标题】:how to convert wchar_t to string in swift如何快速将 wchar_t 转换为字符串
【发布时间】:2015-06-25 07:13:26
【问题描述】:

我想从 C 库中获取一个 wchar_t 数组,并将其转换为 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&lt;Int8&gt;.alloc(Int(bufLen)),我们可以使用String.fromCString(buf)!转换它。

如果我 println(buf[0]),它打印一个整数 67,它是 'C' 的 ascii 值,我怎样才能 println(buf[0]) 作为 'C' 而不是 0? 谢谢!

【问题讨论】:

    标签: c swift


    【解决方案1】:

    wchar_tInt32 的别名,包含一个 UTF-32 代码点 以主机字节顺序(在所有当前的 iOS 和 OS X 上都是 little-endian 平台)。

    因此,您可以将缓冲区转换为 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 字符串 是零终止的。)

    【讨论】:

    • 谢谢!你的更好
    • 你肯定知道你的wchar_ts
    【解决方案2】:

    使用:

    var char = Character(UnicodeScalar(Int(buf[idx])))
    

    可以将 wchar_t 解释为字符

    【讨论】:

      猜你喜欢
      • 2015-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-09
      • 1970-01-01
      • 2018-09-02
      • 2014-11-12
      相关资源
      最近更新 更多