【问题标题】:Swift to C bridging: String to UnsafePointer<Int8>? is not automatically bridged?Swift 到 C 的桥接:字符串到 UnsafePointer<Int8>?是不是自动桥接?
【发布时间】:2019-02-09 19:39:43
【问题描述】:

在尝试与 C 库 (Vulkan) 交互时,在尝试将 Swift(4.2) 本机字符串分配给 C 字符串时遇到以下错误

error: cannot assign value of type 'String' to type 'UnsafePointer<Int8>?'

我正在做一个简单的任务

var appInfo = VkApplicationInfo()
appInfo.pApplicationName = "Hello world"

难道 Swift 不应该通过其自动桥接来处理这些问题吗?

【问题讨论】:

  • 自动桥接在这里无济于事,因为它不能解决内存管理问题。您将 Swift 字符串传递给不符合 Swift ARC 规则的 C 代码。我认为在这种情况下您需要使用 Unmanaged,但我不确定。
  • @Alexander: Unmanaged&lt;T&gt; 在这里无济于事,它只用于 classes T

标签: c swift vulkan bridging-header


【解决方案1】:

从 Swift String 自动创建 C 字符串表示仅在调用带有 UnsafePointer&lt;Int8&gt; 参数的函数时完成(比较 String value to UnsafePointer<UInt8> function parameter behavior),并且 C 字符串仅在函数的持续时间内有效打电话。

如果 C 字符串只需要有限的生命周期,那么你可以这样做

let str = "Hello world"
str.withCString { cStringPtr in
    var appInfo = VkApplicationInfo()
    appInfo.pApplicationName = cStringPtr

    // ...
}

为了更长的生命周期,您可以复制字符串:

let str = "Hello world"
let cStringPtr = strdup(str)! // Error checking omitted for brevity
var appInfo = VkApplicationInfo()
appInfo.pApplicationName = UnsafePointer(cStringPtr)

如果不再需要则释放内存:

free(cStringPtr)

【讨论】:

    猜你喜欢
    • 2021-08-11
    • 1970-01-01
    • 2016-03-26
    • 2015-10-26
    • 2021-12-05
    • 2020-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多