[英]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.