UnsafeMutablePointer to [UInt8] without memory copy

后端 未结 2 1528
抹茶落季
抹茶落季 2021-02-05 23:15

Is it possible to create a [UInt8] from an UnsafeMutablePointer without copying the bytes?

In the NSData world I coul

2条回答
  •  爱一瞬间的悲伤
    2021-02-06 00:00

    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, _ 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)
    

提交回复
热议问题