[英]How do I get a Swift UnsafePointer from an immutable non-class value?
I want to be able to create an UnsafePointer
from immutable values. 我希望能够
UnsafePointer
值创建UnsafePointer
。
The simplest reproduction of what I've tried to do is as follows: 我试图做的最简单的再现如下:
let number : Int = 42;
var pointer = UnsafePointer<Int>(&number);
^
| Could not make `inout Int` from immutable
value.
Since Int
does not conform to AnyObject
, I cannot use unsafeAddressOf()
. 由于
Int
不符合AnyObject
,我不能使用unsafeAddressOf()
。
According to a message in the [swift-evolution] mailing list by Joe Groff , you can simply wrap the variable in an array when passing the pointer to another function. 根据Joe Groff在[swift-evolution]邮件列表中的消息 ,您可以在将指针传递给另一个函数时将变量简单地包装在数组中。 This method creates a temporary array with a copy of the target value and even works in Swift 2 .
此方法创建一个带有目标值副本的临时数组,甚至可以在Swift 2中使用 。
let number : Int = 42
my_c_function([number])
In Swift 3 , you can construct an UnsafePointer
directly. 在Swift 3中 ,您可以直接构造
UnsafePointer
。 However, you must ensure the array's lifecycle matches that of the UnsafePointer
. 但是,您必须确保数组的生命周期与
UnsafePointer
的生命周期相匹配。 Otherwise, the array and the copied value may be overwritten. 否则,可能会覆盖数组和复制的值。
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.
You can use withUnsafePointer. 您可以使用withUnsafePointer。
var number : Int = 42
withUnsafePointer(to: &number) { (pointer: UnsafePointer<Int>) in
// use pointer inside this block
pointer.pointee
}
Alternately, you can use the "$0" shorthand argument to access the pointer within the block. 或者,您可以使用“$ 0”速记参数来访问块内的指针。
var number : Int = 42
withUnsafePointer(to: &number) {
// use pointer inside this block
$0.pointee
}
Here are some good notes about using UnsafePointer: https://developer.apple.com/reference/swift/unsafepointer 以下是使用UnsafePointer的一些好注意事项: https : //developer.apple.com/reference/swift/unsafepointer
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.