As <a title="ArrayFire function list" href="http://www.sandbox.arrayfire.com/docs/group__arrayfire__func.htm" target="_blank">extensive</a> as ArrayFire is, there are a few cases where you are still working with custom CUDA or OpenCL kernels. You may want to integrate ArrayFire into an existing code base for productivity or you may want to keep around the old implementation for testing purposes. In this post we are going to talk about how you can integrate your custom kernels into ArrayFire in a seamless fashion.

First let us look at the code and then break it down bit by bit.

<code>
int main()
{
    // Generate input data
    af::array x = af::randu(num, 1);

    // Create empty array with required dimensions
    af::array y = af::array(num, 1);

    // Get device pointers
    float *d_x = x.device<float>();
    float *d_y = y.device<float>();

    // Finish the tasks arrayfire was doing
    af::sync();

    // Launch kernel to do the following operations
    // y = sin(x)^2 + con(x)^2
    launch_simple_kernel(d_y, d_x, num);

    // Tell arrayfire it controls the pointers again
    x.unlock();
    y.unlock();

    // Check for errors
    // sin(x)^ + cos(x)^2 == 1
    // The following should print 0
    float err = af::sum<float>(y - 1);
    printf("Error: %f\n", err);

    return 0;
}
</code>