gpt4 book ai didi

arrays - 在没有复制或分配的 Swift 数组类型之间进行转换

转载 作者:搜寻专家 更新时间:2023-11-01 06:53:17 24 4
gpt4 key购买 nike

我想访问一个现有的 UInt64 数组,就好像它是一个 Int8 数组一样。关键要求是效率——我不想复制或重新分配数据,只想直接访问。我不想要副作用(例如,我希望能够在执行此代码块后继续使用 uint64Array,正在阅读有关具有未定义副作用的重新绑定(bind)。)

我试着用 Swift 4.2 来做这个:

var uint64Array = [UInt64](repeating: 0, count: 100)

uint64Array.withUnsafeMutableBufferPointer() {
uint64Pointer in
uint64Pointer.withMemoryRebound(to: Int8.self) { // <- Error occurs here.
int8Pointer in
int8Pointer[0] = 1
int8Pointer[1] = 2
int8Pointer[2] = 3
int8Pointer[3] = 4
}
}

但是我在运行时在以下行中遇到 fatal error :

    uint64Pointer.withMemoryRebound(to: Int8.self) {

这是正确的方法吗?如果是这样,为什么我会收到 fatal error ?

最佳答案

我认为问题在于您不能按照文档中的注释直接绑定(bind)到不同的类型:

Only use this method to rebind the buffer’s memory to a type with the same size and stride as the currently bound Element type. To bind a region of memory to a type that is a different size, convert the buffer to a raw buffer and use the bindMemory(to:) method.

如果字节是您所追求的,那么最快的路线是:

var uint64Array = [UInt64](repeating: 0, count: 100)
uint64Array.withUnsafeMutableBytes { x in

x[0] = 1
x[1] = 2
x[3] = 3
x[4] = 4

}

如果您想使用其他类型,您可以这样做:

var uint64Array = [UInt64](repeating: 0, count: 100)

uint64Array.withUnsafeMutableBufferPointer() {
uint64Pointer in

let x = UnsafeMutableRawBufferPointer(uint64Pointer).bindMemory(to: Int32.self)
x[0] = 1
x[1] = 2
x[3] = 3
x[4] = 4

}

关于arrays - 在没有复制或分配的 Swift 数组类型之间进行转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55640583/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com