OpenCL編程中可以使用結構體,只需要在核函數kernel中提供同樣的結構體申明就可以啦。
如果在主函數中定義了結構體:
1 typedef struct studentNode{
2 int age;
3 float height;
4 }student;
主函數中定義數據,並傳輸給OpenCL kernel:
student *stu_input=(student*)malloc(sizeof(studentNode));
stu_input->age=25;
stu_input->height=1.8l;
student *stu_output=(student*)malloc(sizeof(studentNode));
cl_mem inputBuffer = clCreateBuffer(context, CL_MEM_READ_ONLY|CL_MEM_COPY_HOST_PTR, sizeof(studentNode),(void *)stu_input, NULL);
cl_mem outputBuffer = clCreateBuffer(context, CL_MEM_WRITE_ONLY ,sizeof(studentNode), NULL, NULL);
cl_kernel kernel = clCreateKernel(program,"structTest", NULL);
status = clSetKernelArg(kernel, 0, sizeof(cl_mem), (void *)&inputBuffer);
status = clSetKernelArg(kernel, 1, sizeof(cl_mem), (void *)&outputBuffer);
下面是具體的OpenCL kernel,可以對學生的年齡、身高進行修改:
typedef struct studentNode{
int age;
float height;
}student;
int growUp(__global student *stu_input ,__global student *stu_output)
{
stu_output->age=stu_input->age+1;
stu_output->height=stu_input->height + 0.1;
return 0;
}
__kernel void structTest(__global student *stu_input ,__global student *stu_output)
{
growUp(stu_input,stu_output);
}
執行輸出:
注意:
OpenCL中不支持字符串,如char string[32]="Hello World"。OpenCL不能確定字符串中有多少個有效字符,必須給定字符數量。