swift 如何使用结构体向MTLBuffer写入?

mspsb9vt  于 2022-12-22  发布在  Swift
关注(0)|答案(1)|浏览(136)

我有一个包含3个MTLBuffer的数组。创建它们后会重用它们。使用信号量管理它们以避免冲突。我需要使用我创建的结构体写入它们。我在绑定MTLBuffer并将我的结构体格式分配给它时遇到问题。我正在将其从OBJ-C转换为SWIFT。OBJ-C代码工作正常。我在SWIFT "Cast from"中遇到错误(任何MTLBuffer)?'到不相关类型' AAPLUniforms '总是失败"我该怎么做?
该结构体

typedef struct{
matrix_float4x4 mvpMatrix;
float pointSize;} AAPLUniforms;

我在这里创建MTLBuffers数组

/ Create and allocate the dynamic uniform buffer objects.
for i in 0..<AAPLMaxRenderBuffersInFlight {
  // Indicate shared storage so that both the  CPU can access the buffers
  let storageMode: MTLResourceOptions = .storageModeShared
  
  dynamicUniformBuffers[i] = device.makeBuffer(
    length: MemoryLayout<AAPLUniforms>.size,
    options: storageMode)
  
  dynamicUniformBuffers[i]?.label = String(format: "UniformBuffer%lu", i)
}

尝试将MTLBuffer绑定到结构类型时,出现错误"从"(any MTLBuffer)?"到不相关类型" AAPLUniforms "的Cast总是失败"

func updateState() {

var uniforms = dynamicUniformBuffers[currentBufferIndex] as? AAPLUniforms

uniforms?.pointSize = AAPLBodyPointSize
uniforms?.mvpMatrix = projectionMatrix!
}

工作的OBJC代码如下所示

- (void)updateState{
AAPLUniforms *uniforms = (AAPLUniforms *)_dynamicUniformBuffers[_currentBufferIndex].contents;
uniforms->pointSize = AAPLBodyPointSize;
uniforms->mvpMatrix = _projectionMatrix;
afdcj2ne

afdcj2ne1#

你需要的是指向MTLBuffer内容的实际内存的指针。你可以使用它的contents()方法来获得它,该方法将返回一个UnsafeMutableRawPointer。然后你可以调用它的bindMemory方法来将它绑定(强制转换)到UnsafeMutablePointer<AAPLUniforms>。之后,你可以使用它的pointee属性来访问你的AAPLUniforms示例。
我觉得这应该能满足你的要求:

let uniformsPtr = dynamicUniformBuffers[currentBufferIndex]!.contents()
    .bindMemory(to: AAPLUniforms.self, capacity: 1)

uniformsPtr.pointee.pointSize = AAPLBodyPointSize
uniformsPtr.pointee.mvpMatrix = projectionMatrix!

相关问题