gpt4 book ai didi

swift - 如何从 Swift 中的索引开始将内存复制到 UnsafeMutableRawPointer?

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

我知道如何使用以下方法将内存从数组复制到从索引 0 开始的 UnsafeMutableRawPointer:

mutableRawPointer.copyMemory(from: bytes, byteCount: bytes.count * MemoryLayout<Float>.stride)

其中 bytes 是一个 float 数组。

但是,我想从我的数组复制到一个从可能不为零的索引开始的可变原始指针。

例如:

let array: [Float] = [1, 2, 3]

copyMemoryStartingAtIndex(to: myPointer, from: array, startIndexAtPointer: 2)

因此,如果指针对象是 [0, 0, 0, 0, 0],它将变为 [0, 0, 1, 2, 3]。

如何在 Swift 4 中实现这一点?

最佳答案

你可以这样写:

//Caution: when T is not a `primitive` type, this code may cause severe memory issue
func copyMemoryStartingAtIndex<T>(to umrp: UnsafeMutableRawPointer, from arr: [T], startIndexAtPointer toIndex: Int) {
let byteOffset = MemoryLayout<T>.stride * toIndex
let byteCount = MemoryLayout<T>.stride * arr.count
umrp.advanced(by: byteOffset).copyMemory(from: arr, byteCount: byteCount)
}

测试代码:

let size = MemoryLayout<Float>.stride * 5
let myPointer = UnsafeMutableRawPointer.allocate(byteCount: size, alignment: MemoryLayout<Float>.alignment)
defer {myPointer.deallocate()}

let uint8ptr = myPointer.initializeMemory(as: UInt8.self, repeating: 0, count: size)
defer {uint8ptr.deinitialize(count: size)}

func dump(_ urp: UnsafeRawPointer, _ size: Int) {
let urbp = UnsafeRawBufferPointer(start: urp, count: size)
print(urbp.map{String(format: "%02X", $0)}.joined(separator: " "))
}

let array: [Float] = [1, 2, 3]

dump(myPointer, size)
copyMemoryStartingAtIndex(to: myPointer, from: array, startIndexAtPointer: 2)
dump(myPointer, size)

输出:

00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 80 3F 00 00 00 40 00 00 40 40

但是,我建议您考虑 Hamish 在评论中所说的话。

关于swift - 如何从 Swift 中的索引开始将内存复制到 UnsafeMutableRawPointer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52803146/

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