次のように書くことができます。
//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
ただし、コメントでハミッシュが言っていることを検討することをお勧めします。