ios – 金属着色语言 – (控制台)输出?

我可以使用控制台输出调试我的金属着色语言代码(比如在 Swift中打印)吗?

如果有,怎么样?

如果不是,有没有其他方法从我的.Metal文件输出变量? (也许通过使用commandEncoder-buffer将数据从.Metal文件传递到我的.swift文件?)

我没有成功尝试通过commandEncoder传递对Int变量(在我的.swift文件中)的引用到我的.Metal文件.在.Metal文件中,我为int变量赋值,但是如果我在swift文件中打印Int,则指定的值不存在.

.swift文件

...
var myMetalOutput: Int = 0
...
let printBuffer = device.newBufferWithBytes(&myMetalOutput,length: sizeof(Int),options: MTLResourceOptions.cpuCacheModeDefaultCache)
commandEncoder.setBuffer(printBuffer,offset: 0,atIndex: 8)
...
commandBuffer.commit()
drawable.present()
print("myMetalOutput: \(myMetalOutput)")
...

.Metal文件

...
kernel void shader(...,device int &printBuffer [[8]],...) {
...
printBuffer = 123;
...
}

控制台输出始终为myMetalOutput:0

解决方法

如果有人需要,这是一个有效的解决方案:
let device = MTLCreateSystemDefaultDevice()!
let commandQueue = device.newCommandQueue()
let defaultLibrary = device.newDefaultLibrary()!
let commandBuffer = commandQueue.commandBuffer()
let computeCommandEncoder = commandBuffer.computeCommandEncoder()

let program = defaultLibrary.newFunctionWithName("shader")

do
{
    let computePipelineFilter = try device.newComputePipelinestateWithFunction(program!)
    computeCommandEncoder.setComputePipelinestate(computePipelineFilter)
    var resultdata = [Int](count: 1,repeatedValue: 0)
    let outVectorBuffer = device.newBufferWithBytes(&resultdata,length: sizeofValue(1),options: MTLResourceOptions.cpuCacheModeDefaultCache)
    computeCommandEncoder.setBuffer(outVectorBuffer,atIndex: 0)


    let threadsPerGroup = MTLSize(width:1,height:1,depth:1)
    let numThreadgroups = MTLSize(width:1,depth:1)
    computeCommandEncoder.dispatchThreadgroups(numThreadgroups,threadsPerThreadgroup: threadsPerGroup)


    computeCommandEncoder.endEncoding()

    commandBuffer.addCompletedHandler {commandBuffer in
        let data = NSData(bytes: outVectorBuffer.contents(),length: sizeof(NSInteger))
        var out: NSInteger = 0
        data.getBytes(&out,length: sizeof(NSInteger))
        print("data: \(out)")
    }

    commandBuffer.commit()

}
catch
{
    fatalError("newComputePipelinestateWithFunction Failed ")
}

着色器:

kernel void shader(device int &printBuffer [[buffer(0)]],uint id [[ thread_position_in_grid ]]) {

    printBuffer = 123;

}

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...