Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将内存复制到从Swift中的索引开始的UnsafemtableRawPointer?_Swift_Pointers_Unsafe Pointers_Unsafemutablepointer - Fatal编程技术网

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

如何将内存复制到从Swift中的索引开始的UnsafemtableRawPointer?,swift,pointers,unsafe-pointers,unsafemutablepointer,Swift,Pointers,Unsafe Pointers,Unsafemutablepointer,我知道如何使用以下命令将内存从数组复制到从索引0开始的UnsafemtableRawPointer: mutableRawPointer.copyMemory(from: bytes, byteCount: bytes.count * MemoryLayout<Float>.stride) 因此,如果指针对象是[0,0,0,0,0],它将变成[0,0,1,2,3] 如何在Swift 4中实现这一点?您可以这样写: //Caution: when T is not a `primit

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

mutableRawPointer.copyMemory(from: bytes, byteCount: bytes.count * MemoryLayout<Float>.stride)
因此,如果指针对象是[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)
}

<>但是,我建议你考虑一下Hamish在评论中所说的。

<代码>(MutabravaPosith+ByTeOffice)。尽管我强烈建议,如果您知道底层内存绑定到给定类型,则使用类型化指针。它实际上是由MTLBuffer中的
contents
func给定的指针。
//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