1

I know how to copy memory from an array to an UnsafeMutableRawPointer starting at index 0 by using:

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

where bytes is an array of floats.

However, I would like to copy from my array to a mutable raw pointer starting from an index that might not be zero.

Eg.:

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

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

So, if the pointee was [0, 0, 0, 0, 0], it will become [0, 0, 1, 2, 3].

How can I achieve this in Swift 4?

4

1 回答 1

3

你可以这样写:

//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 在评论中所说的话。

于 2018-10-14T14:57:22.037 回答