对于上下文:我正在尝试使用非常方便的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*
的代码不正确。有人能指出我正确的方向......?
ADDENDUM:感谢@MartinR的回答。看起来该块'消耗'其中使用的任何指针。因此,例如,使用
编写字符串时("Hello".withWideChars({ wCharacters in
xlSheetWriteStrW(newSheet, destRow, destColumn, wCharacters, aFormatHandle)
})
执行aFormatHandle
行后,writeStr
将无效,且无法重复使用。必须为每个写命令创建一个新的FormatHandle
。
答案 0 :(得分: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)
}
}
并且清理是自动的。