我尝试使用用C编写的库。我已经在Xcode项目中导入了.a
和.h
个文件,并检查它是否正常工作。我已经让他们在Objective-C上工作了,现在他们正在为Swift工作。
我遇到的一个问题是功能'参数。有一个函数需要一个参数widechar
(在库中定义为typedef Unsigned short int
),在Swift中是UnsafeMutablePointer<UInt16>
。该函数将其转换并返回结果。
所以我应该将String
转换为UnsafeMutablePointer<UInt16>
。我试图找到转换它的正确方法,但我只是将其转换为UnsafeMutablePointer<UInt8>
。我无法找到有关将String
转换为UnsafeMutablePointer<UInt16>
的答案/信息。
这是我编写的源代码。
extension String{
var utf8CString: UnsafePointer<Int8> {
return UnsafePointer((self as NSString).utf8String!)
}
}
func translate(toBraille: String, withTable: String) -> [String]? {
let filteredString = toBraille.onlyAlphabet
let table = withTable.utf8CString
var inputLength = CInt(filteredString.count)
var outputLength = CInt(maxBufferSize)
let inputValue = UnsafeMutablePointer<widechar>.allocate(capacity: Int(outputLength))
let outputValue = UnsafeMutablePointer<widechar>.allocate(capacity: Int(outputLength))
lou_translateString(table, inputValue, &inputLength, outputValue, &outputLength, nil, nil, 0)
//This is a function that I should use.
let result:[String] = []
return result
}
答案 0 :(得分:2)
您必须使用Swift的UTF-16表示创建一个数组 您可以传递给函数的字符串,并在返回时创建 来自UTF-16数组结果的Swift字符串。
为简单起见,假设C函数作为
导入Swiftfunc translateString(_ source: UnsafeMutablePointer<UInt16>, _ sourceLen: UnsafeMutablePointer<CInt>,
_ dest: UnsafeMutablePointer<UInt16>, _ destLen: UnsafeMutablePointer<CInt>)
然后以下内容应该有效(内联说明):
// Create array with UTF-16 representation of source string:
let sourceString = "Hello world"
var sourceUTF16 = Array(sourceString.utf16)
var sourceLength = CInt(sourceUTF16.count)
// Allocate array for UTF-16 representation of destination string:
let maxBufferSize = 1000
var destUTF16 = Array<UInt16>(repeating: 0, count: maxBufferSize)
var destLength = CInt(destUTF16.count)
// Call translation function:
translateString(&sourceUTF16, &sourceLength, &destUTF16, &destLength)
// Create Swift string from UTF-16 representation in destination buffer:
let destString = String(utf16CodeUnits: destUTF16, count: Int(destLength))
我假设C函数更新destLength
以反映
返回时翻译的字符串的实际长度。