`UnsafePointer` 机制能否显示数据缓冲区中的向量数组以供在 SceneKit 中使用?

Can the `UnsafePointer` mechanism reveal an array of vectors in a Data buffer for use in SceneKit?

我有一个二进制文件,其中包含许多 Float 值的三元组;它实际上是一个 SCNVector3 的长数组,代表 SCNGeometrySource 的顶点。我将文件(请原谅遗漏了 do-try-catch 等)读入内存:

let sceneVectors = Data(contentsOf: sceneURL)

并希望将内存数据作为 [SCNVector3] 传递给 SceneKit:

let sceneGeometry = SCNGeometrySource(vertices: sceneVectors)

我今天一直在努力使用 UnsafePointer 机制将 Data 缓冲区的内容重新键入为 SCNVector3 的数组以满足 SCNGeometrySource合同;像这样。

dataBuffer.withUnsafeBytes { 
    (vertexBuffer: UnsafePointer<SCNVector3>) -> SCNGeometry in
        « magic happens here »
        return sceneGeometry
}

我对这个的阅读告诉我,在闭包内,缓冲区可以作为 SCNVector3 的数组访问,但是当传递给 SCNGeometrySource 时,它会导致 Swift 报告:

cannot convert value of type 'UnsafePointer<SCNVector3>' to expected argument type '[SCNVector3]'

像往常一样,我怀疑有一个我还没有想出的简单解决方案,所以我很感激任何解决这个问题的建议。

SCNGeometrySource(vertices: sceneVectors)你必须通过 向量的 数组 ,而不是指针:

let sceneGeometry = dataBuffer.withUnsafeBytes {
    (vertexBuffer: UnsafePointer<SCNVector3>) -> SCNGeometrySource in
    let sceneVectors = Array(UnsafeBufferPointer(start: vertexBuffer, count: dataBuffer.count/MemoryLayout<SCNVector3>.stride))
    return SCNGeometrySource(vertices: sceneVectors)
}

在 Swift 3 中(但不再在 Swift 4 中)SCNGeometrySource 有另一个初始化程序,它接受一个指向 SCNVector3 的指针和一个计数:

let sceneGeometry = dataBuffer.withUnsafeBytes {
    (vertexBuffer: UnsafePointer<SCNVector3>) -> SCNGeometrySource in
    return SCNGeometrySource(vertices: vertexBuffer, count: dataBuffer.count/MemoryLayout<SCNVector3>.stride)
}

可以缩短为

let sceneGeometry = dataBuffer.withUnsafeBytes {
    SCNGeometrySource(vertices: [=12=], count: dataBuffer.count/MemoryLayout<SCNVector3>.stride)
}