【问题标题】:Convert Swift String to wchar_t将 Swift 字符串转换为 wchar_t
【发布时间】:2018-09-02 05:15:44
【问题描述】:

对于上下文:我正在尝试使用非常方便的LibXL。我已经在 Obj-C 和 C++ 中成功使用了它,但现在正试图移植到 Swift。为了更好地支持Unicode,我需要将所有字符串作为wchar_t*发送到LibXL api。

因此,为此我拼凑了以下代码:

extension String {
    ///Function to convert a String into a wchar_t buffer.
    ///Don't forget to free the buffer!
    var wideChar: UnsafeMutablePointer<wchar_t>? {
        get {
            guard let _cString = self.cString(using: .utf16) else {
                return nil
            }
            let buffer = UnsafeMutablePointer<wchar_t>.allocate(capacity: _cString.count)
            memcpy(buffer, _cString, _cString.count)
            return buffer
        }
    }

对 LibXL 的调用似乎正在工作(获取错误消息的 print 返回“Ok”)。除非我尝试实际写入测试电子表格中的单元格。我得到can't write row 0 in trial version:

if let name = "John Doe".wideChar, let passKey = "mac-f.....lots of characters...3".wideChar {
            xlBookSetKeyW(book, name, passKey)
            print(">: " + String.init(cString: xlBookErrorMessageW(book)))
        }

        if let sheetName = "Output".wideChar, let path = savePath.wideChar, let test = "Hello".wideChar {
            let sheet: SheetHandle = xlBookAddSheetW(book, sheetName, nil)
            xlSheetWriteStrW(sheet, 0, 0, test, sectionTitleFormat)
            print(">: " + String.init(cString: xlBookErrorMessageW(book)))
            let success = xlBookSaveW(book, path)
            dump(success)
            print(">: " + String.init(cString: xlBookErrorMessageW(book)))
        }

我假设我转换为wchar_t* 的代码不正确。有人可以为我指出正确的方向吗..?

附录:感谢@MartinR 的回答。该块似乎“消耗”了其中使用的任何指针。因此,例如,当使用

编写字符串时
("Hello".withWideChars({ wCharacters in
   xlSheetWriteStrW(newSheet, destRow, destColumn, wCharacters, aFormatHandle)
})

aFormatHandle 将在writeStr 行执行后变为无效且不可重复使用。需要为每个写命令创建一个新的FormatHandle。

【问题讨论】:

  • 在发布问题之前研究您的问题。 stackoverflow.com/questions/31043593/…
  • 公平地说,我就是这样做的,这就是我获得扩展名的方式——我应该编辑以显示各种来源。可能您提供的链接没有出现,因为它是 wchar_t 到 String。但它仍然可以使用,所以我会进一步检查。

标签: swift string wchar-t libxl


【解决方案1】:

这里有不同的问题。首先,String.cString(using:) 确实 不适用于多字节编码:

print("ABC".cString(using: .utf16)!)
// [65, 0]  ???

其次,wchar_t 包含 UTF-32 代码点,而不是 UTF-16。 最后,在

let buffer = UnsafeMutablePointer<wchar_t>.allocate(capacity: _cString.count)
memcpy(buffer, _cString, _cString.count)

分配大小不包括结尾的空字符, 并且副本复制_cString.count 字节,不是字符。

所有这些都可以修复,但我建议使用不同的 API (类似于String.withCString(_:)方法):

extension String {
    /// Calls the given closure with a pointer to the contents of the string,
    /// represented as a null-terminated wchar_t array.
    func withWideChars<Result>(_ body: (UnsafePointer<wchar_t>) -> Result) -> Result {
        let u32 = self.unicodeScalars.map { wchar_t(bitPattern: $0.value) } + [0]
        return u32.withUnsafeBufferPointer { body($0.baseAddress!) }
    }
}

然后可以像这样使用

let name = "John Doe"
let passKey = "secret"

name.withWideChars { wname in
    passKey.withWideChars { wpass in
        xlBookSetKeyW(book, wname, wpass)
    }
}

并且清理是自动的。

【讨论】:

  • 很好的答案。我现在只是想了解一下签名! :)
猜你喜欢
  • 1970-01-01
  • 2014-11-12
  • 1970-01-01
  • 2011-02-03
  • 2015-02-27
  • 2012-03-30
  • 1970-01-01
  • 2012-09-09
相关资源
最近更新 更多