简体   繁体   中英

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

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?

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.

If the C string is only need for a limited lifetime then you can do

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM