Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a Swift UnsafePointer from an immutable non-class value?

Tags:

swift

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().

like image 297
Randy the Dev Avatar asked Jun 11 '15 03:06

Randy the Dev


1 Answers

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.
like image 119
Andreas Ley Avatar answered Sep 23 '22 06:09

Andreas Ley