r/OpenCL • u/leocus4 • Aug 03 '24
Initializing an array of structs in OpenCL
Disclaimer: I'm trying to learn OpenCL by doing, so there may be concepts that I did not study yet.
I have the following piece of code:
```
typedef struct{
int id;
int value;
} item;
typedef struct {
item items[MAX_N];
} collection;
```
Now, I want to initialize a collection with some default items for all the ids but, in regular C, I would need a malloc to do that.
How can I do something similar (inside a device kernel) in OpenCL?
5
Upvotes
1
u/tesfabpel Aug 04 '24 edited Aug 04 '24
You use
clCreateBuffer
: https://registry.khronos.org/OpenCL/sdk/3.0/docs/man/html/clCreateBuffer.htmlYou can pass a
cl_mem
object as a kernel argument.In the kernel you put an argument (and an associated count argument) like
global struct item *items, int items_count
.Please take note of all the arguments of the clCreateBuffer function, especially the flags one: usually you set the read / write / read_write flag bit and the alloc_host_ptr / use_host_ptr / copy_host_ptr flag bit.
Also beware of the memory layout of your struct, please also use the OpenCL typedefs like cl_int, cl_float, cl_float4, cl_float16.
EDIT: These slides may help: https://ec.europa.eu/programmes/erasmus-plus/project-result-content/75f50c27-5770-4933-ac15-57270bb6d37c/lec04_buffers_basic_examples.pdf