简体   繁体   English

Swift 到 C 的桥接:字符串到 UnsafePointer<Int8> ? 是不是自动桥接?

[英]Swift to C bridging: String to UnsafePointer<Int8>? is not automatically bridged?

While trying to interface with a C library (Vulkan) I am faced with the following error while trying to assign a Swift(4.2) native String to C String在尝试与 C 库 (Vulkan) 交互时,我在尝试将 Swift(4.2) 本机字符串分配给 C 字符串时遇到以下错误

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

I'm doing a simple assignment我在做一个简单的任务

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

Wasn't Swift supposed to handle these through its automatic bridging? Swift 不应该通过它的自动桥接来处理这些吗?

The automatic creation of a C string representation from a Swift String is only done when calling a function taking a UnsafePointer<Int8> argument (compare String value to UnsafePointer<UInt8> function parameter behavior ), and the C string is only valid for the duration of the function call.仅当调用带有UnsafePointer<Int8>参数的函数(将String 值与 UnsafePointer<UInt8> 函数参数行为进行比较)时,才会从 Swift String自动创建 C 字符串表示,并且 C 字符串仅在持续时间内有效的函数调用。

If the C string is only need for a limited lifetime then you can do如果 C 字符串只需要有限的生命周期,那么你可以这样做

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

    // ...
}

For a longer lifetime you can duplicate the string:为了更长的生命周期,您可以复制字符串:

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

and release the memory if it is no longer needed:并在不再需要时释放内存:

free(cStringPtr)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何创建 Swift 类型 UnsafePointer 的实例<UnsafePointer<Int8> ?&gt;! 传递给 C 函数 - How to create instance of Swift type UnsafePointer<UnsafePointer<Int8>?>! to pass to C function 转换 Int8? 到不安全指针<Int8> ? - Convert Int8? to UnsafePointer<Int8>? Swift:将字符串转换为 UnsafeMutablePointer<Int8> - Swift: Turning a String into UnsafeMutablePointer<Int8> 在Swift中使用C const变量作为UnsafePointer - Use C const variable in Swift as UnsafePointer 将 Dart 字符串转换为 dartffi 指针<int8></int8> - Convert Dart String to dartffi Pointer<Int8> UnsafeMutablePointer <Int8> 转换为UTF8字符串 - UnsafeMutablePointer<Int8> to UTF8 String C 中 _int8 数据类型的格式说明符 - Format specifier of _int8 data type in C swift3.0无法转换类型为&#39;[UnsafeMutablePointer的值 <Int8> ]&#39;转换为预期的参数类型&#39;UnsafeMutablePointer <Int8> &#39; - swift3.0 Cannot convert value of type '[UnsafeMutablePointer<Int8>]' to expected argument type 'UnsafeMutablePointer<Int8>?' 当桥接到特定输入上的swift文件时,在c文件中创建的malloc的C字符串丢失 - malloc'd C string created in c file being lost when bridging to swift file on specific input 自动桥接C struct函数到Swift方法 - Automatic bridging of C struct functions to Swift methods
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM