Compiling CoreImage Kernels and Metal files into a metallibrary

I have one CoreImage Kernel with this namespace "extern "C" { namespace coreimage {" which I have imported like this

let kernel: CIColorKernel 
let url = Bundle.main.url(forResource: "default", withExtension: "metallib")! 
let data = try! Data(contentsOf: url) 
kernel = try! CIColorKernel(functionName: "medianBlend", fromMetalLibraryData: data)

and three .metal files with this namespace "using namespace metal;" which I have imported like this:

let metalDevice = MTLCreateSystemDefaultDevice()! 
let defaultLibrary = metalDevice.makeDefaultLibrary()!

I cant seem to find a way which compiles both into one library, even though I have tried it using the xcrun command line tool.

Can anyone help?

Replies

What is your issue exactly ?

For namespace coreimage you need the following import in the metal file :

#include <metal_stdlib>
using namespace metal;
#include <CoreImage/CoreImage.h> // includes CIKernelMetalLib.h


  • I don't think you need any of the MTLCreateSystemDefaultDevice lines from your post. Initialization a CIColorKernel(.., fromMetalLibraryData: ..) should work just fine with the data like you are doing.
  • Is you metal file properly added to the target ?
  • You need the following flags set in build settings :
    • Other Metal Compiler Flags: -fcikernel
    • Add a user-defined setting: MTLLINKER_FLAGS with value -cikernel


It will run fine on device, however I am filing a bug for simulator, see this topic


Last thing. if then it doesn't compile, the issue might come from your metal shader, in which case feel free to share it or start with something simple like this (this one removes the green color, should have something purple-ish) :

#include <metal_stdlib>
using namespace metal;
#include <CoreImage/CoreImage.h> // includes CIKernelMetalLib.h


extern "C" { namespace coreimage {
    float4 colorTransform(sampler src) {
        float4 color = src.sample(src.coord());
        return float4(color.r, 0.0, color.b, 1.0);
    }
}}


Hope this helps.