我希望能够从不可变值创建UnsafePointer
。
我尝试做的最简单的再现如下:
let number : Int = 42;
var pointer = UnsafePointer<Int>(&number);
^
| Could not make `inout Int` from immutable
value.
由于Int
不符合AnyObject
,我无法使用unsafeAddressOf()
。
答案 0 :(得分:2)
根据message in the [swift-evolution] mailing list by Joe Groff,您可以在将指针传递给另一个函数时将变量简单地包装在数组中。此方法创建一个带有目标值副本的临时数组,甚至可以在 Swift 2 中工作。
let number : Int = 42
my_c_function([number])
在 Swift 3 中,您可以直接构建UnsafePointer
。但是,您必须确保数组的生命周期与UnsafePointer
的生命周期相匹配。否则,可能会覆盖数组和复制的值。
let number : Int = 42
// Store the "temporary" array in a variable to ensure it is not overwritten.
let array = [number]
var pointer = UnsafePointer(array)
// Perform operations using the pointer.
答案 1 :(得分:-1)
您可以使用withUnsafePointer。
var number : Int = 42
withUnsafePointer(to: &number) { (pointer: UnsafePointer<Int>) in
// use pointer inside this block
pointer.pointee
}
或者,您可以使用&#34; $ 0&#34;用于访问块内指针的简写参数。
var number : Int = 42
withUnsafePointer(to: &number) {
// use pointer inside this block
$0.pointee
}
以下是关于使用UnsafePointer的一些好注意事项:https://developer.apple.com/reference/swift/unsafepointer