Swift: 将 const char ** 输出参数转换为 String
Swift: convert const char ** output parameter to String
我正在与使用 const char **
作为输出参数的 C++ 库(使用 C 中的 header)进行交互。
在那个库中执行一个方法后,我需要的值就写在那个变量里,例如:
CustomMethod(const char **output)
CustomMethod(&output)
// Using the `output` here
通常,在Swift中可以只传递一个标准的Swift String
作为参数,它会被透明地转换成const char *
(Interacting with C Pointers - Swift Blog).
例如,我已经在同一个库中多次使用以下构造:
// C
BasicMethod(const char *input)
// Swift
let string = "test"
BasicMethod(string)
但是,在使用 const char **
时,我不能像我预期的那样只传递指向 Swift String
的指针:
// C
CustomMethod(const char **output)
// Swift
var output: String?
CustomMethod(&output)
出现错误:
Cannot convert value of type 'UnsafeMutablePointer<String?>' to
expected argument type 'UnsafeMutablePointer<UnsafePointer?>'
(aka 'UnsafeMutablePointer<Optional<UnsafePointer>>')
我让它工作的唯一方法是直接操纵指针:
// C
CustomMethod(const char **output)
// Swift
var output: UnsafePointer<CChar>?
CustomMethod(&output)
let stringValue = String(cString: json)
有什么方法可以使用自动 Swift 字符串到 const char **
转换,还是只适用于 const char *
?
桥接 C 函数需要一个指向 CChar
指针的可变指针,因此您需要提供一个,这里没有自动桥接。
var characters: UnsafePointer<CChar>?
withUnsafeMutablePointer(to: &characters) {
CustomMethod([=10=])
}
if let characters = characters {
let receivedString = String(cString: characters)
print(receivedString)
}
相同的代码,但采用更 FP 的方式:
var characters: UnsafePointer<CChar>?
withUnsafeMutablePointer(to: &characters, CustomMethod)
var receivedString = characters.map(String.init)
print(receivedString)
我正在与使用 const char **
作为输出参数的 C++ 库(使用 C 中的 header)进行交互。
在那个库中执行一个方法后,我需要的值就写在那个变量里,例如:
CustomMethod(const char **output)
CustomMethod(&output)
// Using the `output` here
通常,在Swift中可以只传递一个标准的Swift String
作为参数,它会被透明地转换成const char *
(Interacting with C Pointers - Swift Blog).
例如,我已经在同一个库中多次使用以下构造:
// C
BasicMethod(const char *input)
// Swift
let string = "test"
BasicMethod(string)
但是,在使用 const char **
时,我不能像我预期的那样只传递指向 Swift String
的指针:
// C
CustomMethod(const char **output)
// Swift
var output: String?
CustomMethod(&output)
出现错误:
Cannot convert value of type 'UnsafeMutablePointer<String?>' to expected argument type 'UnsafeMutablePointer<UnsafePointer?>' (aka 'UnsafeMutablePointer<Optional<UnsafePointer>>')
我让它工作的唯一方法是直接操纵指针:
// C
CustomMethod(const char **output)
// Swift
var output: UnsafePointer<CChar>?
CustomMethod(&output)
let stringValue = String(cString: json)
有什么方法可以使用自动 Swift 字符串到 const char **
转换,还是只适用于 const char *
?
桥接 C 函数需要一个指向 CChar
指针的可变指针,因此您需要提供一个,这里没有自动桥接。
var characters: UnsafePointer<CChar>?
withUnsafeMutablePointer(to: &characters) {
CustomMethod([=10=])
}
if let characters = characters {
let receivedString = String(cString: characters)
print(receivedString)
}
相同的代码,但采用更 FP 的方式:
var characters: UnsafePointer<CChar>?
withUnsafeMutablePointer(to: &characters, CustomMethod)
var receivedString = characters.map(String.init)
print(receivedString)