UnsafeMutablePointer< UInt8>到[UInt8],不复制内存 [英] UnsafeMutablePointer<UInt8> to [UInt8] without memory copy
问题描述
是否可以在不复制字节的情况下从UnsafeMutablePointer<UInt8>
创建[UInt8]
?
Is it possible to create a [UInt8]
from an UnsafeMutablePointer<UInt8>
without copying the bytes?
在NSData
世界中,我可以简单地打电话给
In the NSData
world I could simply call
let data = NSData(bytesNoCopy: p, length: n, freeWhenDone: false)
然后包装指针.
推荐答案
如注释中所述,您可以创建一个
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)
这篇关于UnsafeMutablePointer< UInt8>到[UInt8],不复制内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!