Skip to content

Instantly share code, notes, and snippets.

@kirsteins
Last active October 11, 2022 12:25
Show Gist options
  • Star 43 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save kirsteins/6d6e96380db677169831 to your computer and use it in GitHub Desktop.
Save kirsteins/6d6e96380db677169831 to your computer and use it in GitHub Desktop.
Array -> UnsafeMutablePointer -> Array
var initalArray = [1, 2, 3]
let pointer: UnsafeMutablePointer<Int> = UnsafeMutablePointer(initalArray)
let arrary = Array(UnsafeBufferPointer(start: pointer, count: initalArray.count))
@hughesj919
Copy link

// Swift 3.0 Line 2
let pointer: UnsafeMutablePointer = UnsafeMutablePointer(mutating: initalArray)

@capnslipp
Copy link

In Swift 3, you can also skip the pointer step (line 2)let array = Array(UnsafeBufferPointer(start: initialArray, count: initialArray.count)).

I can't discern why this works (it's not like UnsafeBufferPointer is a protocol that Array conforms to), but hey, I'm not complaining.

@kechan
Copy link

kechan commented Nov 30, 2018

Shouldn't this be:

let pointer: UnsafeMutablePointer< Int > = UnsafeMutablePointer(&initalArray)

with the '&'

@Sombre-Osmoze
Copy link

@capnslipp It work because a "Float" or "Int" array is also a ContiguousArray
Some me memory of this array is stored continuously
For more detail please see Apple Documentation

@NazgulLee
Copy link

Hi, according to Apple's document:

The pointer created through implicit bridging of an instance or of an array’s elements is only valid during the execution of the called function. Escaping the pointer to use after the execution of the function is undefined behavior. In particular, do not use implicit bridging when calling an UnsafeMutablePointer initializer.

so, using pointer from

// Swift 3.0 Line 2
let pointer: UnsafeMutablePointer = UnsafeMutablePointer(mutating: initalArray)

is undefined.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment