为什么我得不到这个 Metal 内核的结果

Why don't I get the result of this Metal kernel

我想了解 Metal 计算着色器的工作原理,所以我写了这段代码:

class AppDelegate: NSObject, NSApplicationDelegate {


    var number:Float!
    var buffer:MTLBuffer!


    func applicationDidFinishLaunching(aNotification: NSNotification) {
        // Insert code here to initialize your application
        let metalDevice = MTLCreateSystemDefaultDevice()!
        let library = metalDevice.newDefaultLibrary()!
        let commandQueue = metalDevice.newCommandQueue()
        let commandBuffer = commandQueue.commandBuffer()
        let commandEncoder = commandBuffer.computeCommandEncoder()


        let pointlessFunction = library.newFunctionWithName("pointless")!
        let pipelineState = try! metalDevice.newComputePipelineStateWithFunction(pointlessFunction)
        commandEncoder.setComputePipelineState(pipelineState)
        number = 12

        buffer = metalDevice.newBufferWithBytes(&number, length: sizeof(Float), options: MTLResourceOptions.StorageModeShared)
        commandEncoder.setBuffer(buffer, offset: 0, atIndex: 0)


        commandEncoder.endEncoding()

        commandBuffer.commit()
        commandBuffer.waitUntilCompleted()

        let data = NSData(bytesNoCopy: buffer.contents(), length: sizeof(Float), freeWhenDone: false)
        var newResult:Float = 0
        data.getBytes(&newResult, length: sizeof(Float))
        print(newResult)




    }

通过使用 StorageModeShared 创建缓冲区,我希望在我的 Swift 代码中反映对 Metal 缓冲区所做的更改,但是当我填充 newResult 变量时,看起来缓冲区仍然是与开头相同的值 (12) 而它应该是 125 :

#include <metal_stdlib>
using namespace metal;



kernel void pointless (device float* outData [[ buffer(0) ]]) {

    *outData = 125.0;
}

我做错了什么?

内核函数不会 运行 除非您分派它。我想你假设如果你有一个函数,那么 Metal 应该 运行 它一次,除非你另有说明,但那不会发生。相反,它根本不会 运行。在 endEncoding 之前添加这个就可以了!

let size = MTLSize(width: 1, height: 1, depth: 1)
commandEncoder.dispatchThreadgroups(size, threadsPerThreadgroup: size)