如果您知道每个缓冲区的长度,并且它们都相等。那为什么不这样重写:
主机端:
//Use one struct to organize the data
struct MyStruct{
cl_int values[10];
// ...
};
//Create one only cl::Buffer of N elements of type MyStruct
cl::Buffer mybuff = cl::Buffer(context, CL_MEM_READ_ONLY, in_size * sizeof(MyStruct));
//Run the kernel
设备端:
//Use one struct to organize the data
typedef struct{
int values[10];
// ...
}MyStruct;
__global void pix_reduce
(MyStruct out*, MyStruct* in)
{
// ...
}
您甚至可以将长度“10”定义为 X,并将该定义放入您的代码(主机和 CPU 端)中。另一个不错的选择是一个 BIG 连续内存数组并将分隔长度传递给内核。
注意:我知道很难停止使用指针,但这是要付出的代价,因为内存区域不同。相信我,我已经完成了非常复杂的动态长度结构,稍加思考和重写,它就可以工作了,而且代码也很整洁。
编辑:另一个可以动态改变的解决方案
主机端:
//Data organized as jagged array
std::vector<std::vector<cl_int> > my_data;
//It is supposed to be filled my_Data
//....
//Create one only cl::Buffer of NxM elements of type int
cl::Buffer mybuff = cl::Buffer(context, CL_MEM_READ_ONLY, my_data.size() * my_data[0].size() * sizeof(cl_int));
cl::Buffer mybuff_out = cl::Buffer(context, CL_MEM_WRITE_ONLY, my_data.size() * my_data[0].size() * sizeof(cl_int));
// Copy the jagged array
for(int i=0; i<my_data.size(); i++)
queue.enqueueWriteBuffer(mybuff, CL_FALSE, i * my_data[0].size() * sizeof(cl_int), my_data[0].size() * sizeof(cl_int), &my_data[i][0]);
//Set kernel
kernel.SetArgs(0, mybuff);
kernel.SetArgs(1, mybuff_out);
kernel.SetArgs(2, (cl_int)my_data[0].size());
//Run the kernel
queue.EnqueueNDRangeKernel(...);
设备端:
__kernel void pix_reduce
(_global const int * in, _global int * out, const int size)
{
unsigned int id = get_global_id(0);
for(int i=0; i<size; i++){
out[id*size+i] = out[id*size+i]; //Or any other operation using size as the separation between chunks
}
}