How to get Swift UnsafePointer from an immutable value other than a class?

I want to create an UnsafePointer from immutable values.

The simplest reproduction of what I was trying 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 match AnyObject , I cannot use unsafeAddressOf() .

+5
source share
2 answers

According to a post on the [swift-evolution] mailing list of Joe Groff , you can simply wrap a variable in an array when passing a 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 directly build UnsafePointer . However, you must ensure that the life cycle of the array matches the UnsafePointer parameter. 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. 
+2
source

You can use withUnsafePointer.

 var number : Int = 42 withUnsafePointer(to: &number) { (pointer: UnsafePointer<Int>) in // use pointer inside this block pointer.pointee } 

Alternatively, you can use the $ 0 transcript to access the pointer inside 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

-1
source

All Articles