UnsafeMutablePointer<UInt8> to [UInt8] without memory copy

As already mentioned in the comments, you can create an UnsafeMutableBufferPointer from the pointer:

let a = UnsafeMutableBufferPointer(start: p, count: n)

This does not copy the data, which means that you have to ensure that the pointed-to data is valid as long as a is used. Unsafe (mutable) buffer pointers have similar access methods like arrays, such as subscripting:

for i in 0 ..< a.count {
    print(a[i])
}

or enumeration:

for elem in a {
    print(elem)
}

You can create a "real" array from the buffer pointer with

let b = Array(a)

but this will copy the data.

Here is a complete example demonstrating the above statements:

func test(_ p : UnsafeMutablePointer<UInt8>, _ n : Int) {

    // Mutable buffer pointer from data:
    let a = UnsafeMutableBufferPointer(start: p, count: n)
    // Array from mutable buffer pointer
    let b = Array(a)

    // Modify the given data:
    p[2] = 17

    // Printing elements of a shows the modified data: 1, 2, 17, 4
    for elem in a {
        print(elem)
    }

    // Printing b shows the orignal (copied) data: 1, 2, 3, 4
    print(b)

}

var bytes : [UInt8] = [ 1, 2, 3, 4 ]
test(&bytes, bytes.count)

Tags:

Pointers

Swift