283
|
1 #include <stdio.h>
|
|
2 #include <stdlib.h>
|
|
3
|
|
4 #ifdef __APPLE__
|
|
5 #include <OpenCL/opencl.h>
|
|
6 #else
|
|
7 #include <CL/cl.h>
|
|
8 #endif
|
|
9
|
|
10 #define MEM_SIZE (128)
|
|
11 #define MAX_SOURCE_SIZE (0x100000)
|
|
12
|
|
13 int main()
|
|
14 {
|
|
15 cl_device_id device_id = NULL;
|
|
16 cl_context context = NULL;
|
|
17 cl_command_queue command_queue = NULL;
|
|
18 cl_mem memobj = NULL;
|
|
19 cl_program program = NULL;
|
|
20 cl_kernel kernel = NULL;
|
|
21 cl_platform_id platform_id = NULL;
|
|
22 cl_uint ret_num_devices;
|
|
23 cl_uint ret_num_platforms;
|
|
24 cl_int ret;
|
|
25
|
|
26 char string[MEM_SIZE];
|
|
27
|
|
28 FILE *fp;
|
|
29 char fileName[] = "./hello.cl";
|
|
30 char *source_str;
|
|
31 size_t source_size;
|
|
32
|
|
33 /* Load the source code containing the kernel*/
|
|
34 fp = fopen(fileName, "r");
|
|
35 if (!fp) {
|
|
36 fprintf(stderr, "Failed to load kernel.\n");
|
|
37 exit(1);
|
|
38 }
|
|
39 source_str = (char*)malloc(MAX_SOURCE_SIZE);
|
|
40 source_size = fread(source_str, 1, MAX_SOURCE_SIZE, fp);
|
|
41 fclose(fp);
|
|
42
|
|
43 /* Get Platform and Device Info */
|
|
44 ret = clGetPlatformIDs(1, &platform_id, &ret_num_platforms);
|
|
45 ret = clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_DEFAULT, 1, &device_id, &ret_num_devices);
|
|
46
|
|
47 /* Create OpenCL context */
|
|
48 context = clCreateContext(NULL, 1, &device_id, NULL, NULL, &ret);
|
|
49
|
|
50 /* Create Command Queue */
|
|
51 command_queue = clCreateCommandQueue(context, device_id, 0, &ret);
|
|
52
|
|
53 /* Create Memory Buffer */
|
|
54 memobj = clCreateBuffer(context, CL_MEM_READ_WRITE,MEM_SIZE * sizeof(char), NULL, &ret);
|
|
55
|
|
56 /* Create Kernel Program from the source */
|
|
57 program = clCreateProgramWithSource(context, 1, (const char **)&source_str,
|
|
58 (const size_t *)&source_size, &ret);
|
|
59
|
|
60 /* Build Kernel Program */
|
|
61 ret = clBuildProgram(program, 1, &device_id, NULL, NULL, NULL);
|
|
62
|
|
63 /* Create OpenCL Kernel */
|
|
64 kernel = clCreateKernel(program, "hello", &ret);
|
|
65
|
|
66 /* Set OpenCL Kernel Parameters */
|
|
67 ret = clSetKernelArg(kernel, 0, sizeof(cl_mem), (void *)&memobj);
|
|
68
|
|
69 /* Execute OpenCL Kernel */
|
|
70 ret = clEnqueueTask(command_queue, kernel, 0, NULL,NULL);
|
|
71
|
|
72 /* Copy results from the memory buffer */
|
|
73 ret = clEnqueueReadBuffer(command_queue, memobj, CL_TRUE, 0,
|
|
74 MEM_SIZE * sizeof(char),string, 0, NULL, NULL);
|
|
75
|
|
76 /* Display Result */
|
|
77 puts(string);
|
|
78
|
|
79 /* Finalization */
|
|
80 ret = clFlush(command_queue);
|
|
81 ret = clFinish(command_queue);
|
|
82 ret = clReleaseKernel(kernel);
|
|
83 ret = clReleaseProgram(program);
|
|
84 ret = clReleaseMemObject(memobj);
|
|
85 ret = clReleaseCommandQueue(command_queue);
|
|
86 ret = clReleaseContext(context);
|
|
87
|
|
88 free(source_str);
|
|
89
|
|
90 return 0;
|
|
91 }
|