虽然试图用C语言库接口(福尔康)我遇到下面的错误,而试图分配斯威夫特(4.2)本地字符串到C字符串
error: cannot assign value of type 'String' to type 'UnsafePointer<Int8>?'
我做一个简单的任务
var appInfo = VkApplicationInfo()
appInfo.pApplicationName = "Hello world"
是不是应该雨燕通过自动桥接来处理这些?
自动创建从斯威夫特String
C字符串表示的调用函数采取UnsafePointer<Int8>
参数(比较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)