对于上下文:我正在尝试使用非常方便的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)
})
writeStr
行执行后,aFormatHandle
将变为无效,并且不可重用。有必要为每个写入命令创建一个新FormatHandle
。
这里有不同的问题。首先,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)
}
}
清理是自动的。