How to pass array in kernel, do something and then return it - OpenCL

c++, opencl

Solution

Your calls to `clSetKernelArg()` are invalid - you should be passing the OpenCL buffer, not the host pointer. For example:

ret = clSetKernelArg(kernel, 0, sizeof(cl_mem), &memobj);
ret = clSetKernelArg(kernel, 1, sizeof(cl_mem), &memobj2);

As was already pointed out, you should check the return codes from every OpenCL runtime API call. This would point you towards the error pretty quickly.

Problem

I am trying to pass an array to OpenCL kernel, then do something with it and pass it back to host. I have modified code in this tutorial. This is just kernel for figuring out how OpenCL actually works. I hope that this would just substract 2 from the first element of array1 and store it into the first element of array2: ``` __kernel void test(global int* array1, global int* array2) { array2[0] = array1[0] - 2; } ``` In main I have two arrays, one (host1) with some numbers and the second (host2) initialized to zeros. Than to create memory buffers I use: ``` memobj = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, MEM_SIZE * sizeof(int), &host1, &ret); memobj2 = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, MEM_SIZE * sizeof(int), &host2, &ret); ``` After building program I set arguments: ``` ret = clSetKernelArg(kernel, 0, sizeof(cl_mem), &host1); ret = clSetKernelArg(kernel, 1, sizeof(cl_mem), &host2); ``` And then after execution I try to get that array back. ``` ret = clEnqueueReadBuffer(command_queue, memobj2, CL_TRUE, 0, MEM_SIZE * sizeof(int), host2, 0, NULL, NULL); ``` Here if I change memobj2 to memobj the host2 will contain values of host1, otherwise it stays the same. I guess that this is not how one will return arrays. I am stuck at this point.

Original source