且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

UnsafeMutablePointer< UInt8>到[UInt8],不复制内存

更新时间:2023-02-02 09:51:46

如注释中所述,您可以创建一个 UnsafeMutableBufferPointer来自指针:

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

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

这不会复制数据,这意味着必须确保 只要使用a,指向的数据就有效. 不安全(可变)缓冲区指针具有类似的访问方法,例如数组, 例如下标:

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])
}

或枚举:

for elem in a {
    print(elem)
}

您可以使用

let b = Array(a)

但这将复制数据.

下面是一个完整的示例,演示了以上语句:

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)