0

我想做这个自定义 CIFilter。

var dummyColors = [
        CIVector(x: 0.9, y: 0.3, z: 0.4),
        CIVector(x: 0.2, y: 0.5, z: 0.9),
        CIVector(x: 0.5, y: 0.9, z: 0.3)
    ]
    
    var normal = dummyColors.withUnsafeMutableBufferPointer { (buffer) -> UnsafeMutablePointer<CIVector> in
        var p = buffer.baseAddress
        print(p)
        return p!
    }

    //this is  parameter and how to pass bvalue to the kernel function
    return self.kernel.apply(extent: inputExtent,
                             roiCallback: roiCallback,
                             arguments: [inputImage, reddish, greenish, blueish, normal])  // (5)

这是我试图用指针传递参数。但是代码似乎不喜欢它,它只是崩溃而没有打印错误。

这是金属功能

extern "C" { namespace coreimage {               // (3)

//this is how you define parameter on the top of the function
float4 dyeInThree(sampler src,
                  float3 redVector,
                  float3 greenVector,
                  float3 blueVector,
                  device float3 *a) 

还有另一种方法如何将参数传递给我的金属代码?

4

2 回答 2

0

您获得的指针withUnsafeMutableBufferPointer仅在您传递给函数的闭包内有效。您需要为参数分配更“永久”的存储空间。

您可以从使用诸如UnsafeMutableBufferPointer.allocate分配内存之类的东西开始,但您必须在某处跟踪内存,因为在使用完之后您将需要deallocate它。

于 2021-09-09T17:08:54.657 回答
0

我对您的用例采用了这个答案: https ://stackoverflow.com/a/58706038/16896928

这是我用于内存分配的内容:

var dummyColors = [
            SIMD3<Float>(x: 1.1, y: 0.1, z: 0.1), 
            SIMD3<Float>(x: 0.1, y: 1.1, z: 0.1),
            SIMD3<Float>(x: 0.1, y: 0.1, z: 1.1)
        ]

let pointer = UnsafeMutableRawPointer.allocate(
            byteCount: 3 * MemoryLayout<SIMD3<Float>>.stride,
            alignment: MemoryLayout<SIMD3<Float>>.alignment)
let sPointer = dummyColors.withUnsafeMutableBufferPointer { (buffer) -> UnsafeMutablePointer<SIMD3<Float>> in
            let p = pointer.initializeMemory(as: SIMD3<Float>.self,
            from: buffer.baseAddress!,
            count: buffer.count)
            return p
        }
let data = Data(bytesNoCopy: sPointer, count: 3 * MemoryLayout<SIMD3<Float>>.stride, deallocator: .free)

在将缓冲区传递给内核之前,您需要将其转换为 NSData。这是 Metal 函数声明:

extern "C" { namespace coreimage {               // (3)
    float4 dyeInThree(sampler src,
                      float3 redVector,
                      float3 greenVector,
                      float3 blueVector,
                      constant float3 a[]) {

请注意“常量”命名空间而不是“设备”。否则 Metal 编译器会在运行时出错。

于 2021-09-14T16:28:08.157 回答