【问题标题】:Swift: convert const char ** output parameter to StringSwift:将 const char ** 输出参数转换为字符串
【发布时间】:2021-09-05 05:20:25
【问题描述】:

我正在与使用 const char ** 作为输出参数的 C++ 库(带有 C 中的标头)进行交互。

在那个库中执行了一个方法后,我需要的值就写在那个变量里了,例如:

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)

得到一个错误:

无法将“UnsafeMutablePointer”类型的值转换为 预期参数类型'UnsafeMutablePointer' (又名'UnsafeMutablePointer>')

我可以让它工作的唯一方法是直接操作指针:

// C
CustomMethod(const char **output)

// Swift
var output: UnsafePointer<CChar>?
CustomMethod(&output)
let stringValue = String(cString: json)

有什么方法可以使用自动 Swift 字符串到const char ** 的转换,还是只适用于const char *

【问题讨论】:

  • 要回答最后一段的问题 - 不,自动转换是不可能的,你必须编写一些 Swift 指针代码。

标签: ios c swift pointers char


【解决方案1】:

桥接的 C 函数需要一个指向 CChar 指针的可变指针,因此您需要提供一个,这里没有自动桥接。

var characters: UnsafePointer<CChar>?
withUnsafeMutablePointer(to: &characters) {
    CustomMethod($0)
}

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)

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
  • 2020-05-08
  • 2013-02-15
相关资源
最近更新 更多