Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/20.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加载金属中的默认库_Swift_Initialization_Shader_Metal - Fatal编程技术网

无法使用Swift加载金属中的默认库

无法使用Swift加载金属中的默认库,swift,initialization,shader,metal,Swift,Initialization,Shader,Metal,对于我的项目(作为框架编译),我有一个文件ops.metal: kernel void add(device float *lhs [[buffer(0)]], device float *rhs [[buffer(1)]], device float *result [[buffer(2)]], uint id [[ thread_position_in_grid ]]) { result[

对于我的项目(作为框架编译),我有一个文件
ops.metal

kernel void add(device float *lhs [[buffer(0)]],
                device float *rhs [[buffer(1)]],
                device float *result [[buffer(2)]],
                uint id [[ thread_position_in_grid ]])
{
    result[id] = lhs[id] + rhs[id];
}
以及以下Swift代码:

@available(OSX 10.11, *)
public class MTLContext {
    var device: MTLDevice!
    var commandQueue:MTLCommandQueue!
    var library:MTLLibrary!
    var commandBuffer:MTLCommandBuffer
    var commandEncoder:MTLComputeCommandEncoder

    init() {
        if let defaultDevice = MTLCreateSystemDefaultDevice() {
            device = defaultDevice
            print("device created")
        } else {
            print("Metal is not supported")
        }

        commandQueue = device.makeCommandQueue()

        library = device.newDefaultLibrary()
        if let defaultLibrary = device.newDefaultLibrary() {
            library = defaultLibrary
        } else {
            print("could not load default library")
        }

        commandBuffer = commandQueue.makeCommandBuffer()
        commandEncoder = commandBuffer.makeComputeCommandEncoder()
    }

    deinit {
        commandEncoder.endEncoding()
    }
}
当我尝试在单元测试中创建
MTLContext
的实例时,设备已创建,但无法创建默认库(“code>无法加载默认库”)。我已经检查了编译的框架在
参考资料
中是否有一个
default.metallib
(这是
newDefaultLibrary
最常见的原因)

不幸的是,我还没有找到任何在金属着色器文件中创建计算
内核的工作示例(有一些示例使用性能着色器,但它们不需要在着色器文件中创建内核)

如有任何建议,将不胜感激

newDefaultLibrary()
从当前运行的应用程序的主捆绑包中加载。它不会在任何嵌入式框架或其他位置搜索库

如果要使用编译到嵌入式框架中的metallib,最简单的方法是获取对其包含的
Bundle
的引用,并请求该Bundle的默认库:

let frameworkBundle = Bundle(for: SomeClassFromMyShaderFramework.self)
guard let defaultLibrary = try? device.makeDefaultLibrary(bundle: frameworkBundle) else {
    fatalError("Could not load default library from specified bundle")
}
这确实要求在包含着色器的框架中至少有一个公开可见的类,但这可以非常简单,只需声明一个空类即可完成包查找:

public class SomeClassFromMyShaderFramework {}

太棒了,谢谢你!如果文档中提到这个细节,那就太好了。。。不过,我想大多数人并不是在围绕金属创建框架。