I want to be able to create an UnsafePointer from immutable values.
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().
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. This method creates a temporary array with a copy of the target value and even works in Swift 2.
let number : Int = 42
my_c_function([number])
In Swift 3, you can construct an UnsafePointer directly. However, you must ensure the array's lifecycle matches that of the 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With