Randy the Dev
Randy the Dev

Reputation: 26700

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.

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

Upvotes: 6

Views: 1286

Answers (2)

Andreas Ley
Andreas Ley

Reputation: 9335

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.

Upvotes: 3

Chris Livdahl
Chris Livdahl

Reputation: 4740

You can use 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.

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

Upvotes: 0

Related Questions