| 39 | using std::vector; |
| 40 | |
| 41 | int main() { |
| 42 | // 1. Set up the OpenCL context, device, and queues |
| 43 | cl::Context context; |
| 44 | try { |
| 45 | context = cl::Context(CL_DEVICE_TYPE_ALL); |
| 46 | } catch (const cl::Error& err) { |
| 47 | fprintf(stderr, "Exiting creating context"); |
| 48 | return EXIT_FAILURE; |
| 49 | } |
| 50 | vector<cl::Device> devices = context.getInfo<CL_CONTEXT_DEVICES>(); |
| 51 | if (devices.empty()) { |
| 52 | fprintf(stderr, "Exiting. No devices found"); |
| 53 | return EXIT_SUCCESS; |
| 54 | } |
| 55 | cl::Device device = devices[0]; |
| 56 | cl::CommandQueue queue(context, device); |
| 57 | |
| 58 | // Create a buffer of size 10 filled with ones, copy it to the device |
| 59 | int length = 10; |
| 60 | vector<float> h_A(length, 1); |
| 61 | cl::Buffer cl_A(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, |
| 62 | length * sizeof(float), h_A.data()); |
| 63 | |
| 64 | // 2. Instruct OpenCL to complete its operations using clFinish (or similar) |
| 65 | queue.finish(); |
| 66 | |
| 67 | // 3. Instruct ArrayFire to use the user-created context |
| 68 | // First, create a device from the current OpenCL device + context + |
| 69 | // queue |
| 70 | afcl::addDevice(device(), context(), queue()); |
| 71 | // Next switch ArrayFire to the device using the device and context as |
| 72 | // identifiers: |
| 73 | afcl::setDevice(device(), context()); |
| 74 | |
| 75 | // 4. Create ArrayFire arrays from OpenCL memory objects |
| 76 | af::array af_A = afcl::array(length, cl_A(), f32, true); |
| 77 | clRetainMemObject(cl_A()); |
| 78 | |
| 79 | // 5. Perform ArrayFire operations on the Arrays |
| 80 | af_A = af_A + af::randu(length); |
| 81 | |
| 82 | // NOTE: ArrayFire does not perform the above transaction using in-place |
| 83 | // memory, thus the underlying OpenCL buffers containing the memory |
| 84 | // containing memory to probably have changed |
| 85 | |
| 86 | // 6. Instruct ArrayFire to finish operations using af::sync |
| 87 | af::sync(); |
| 88 | |
| 89 | // 7. Obtain cl_mem references for important memory |
| 90 | cl_mem* af_mem = af_A.device<cl_mem>(); |
| 91 | cl_A = cl::Buffer(*af_mem, /*retain*/ true); |
| 92 | |
| 93 | /// Delete the af_mem pointer. The buffer returned by the device pointer is |
| 94 | /// still valid |
| 95 | delete af_mem; |
| 96 | |
| 97 | // 8. Continue your OpenCL application |
| 98 | |