OpenCL:使用struct作为内核参数 [英] OpenCL: using struct as kernel argument
问题描述
我可以使用struct作为OpenCL内核参数吗?
Can I use struct as OpenCL kernel argument?
我想在NVIDIA OpenCL 1.2(NVIDIA驱动程序352.39)中使用结构类型作为OpenCL内核参数
I want to use struct type as OpenCL kernel argument in NVIDIA OpenCL 1.2 (NVIDIA driver 352.39)
我尝试过,但是会导致CL_OUT_OF_RESOURCE错误.
I tried, but it makes CL_OUT_OF_RESOURCE error.
我的代码有什么问题?
[用于结构定义]
/* struct type definition */
typedef struct _st_foo
{
int aaa;
int bbb;
.....
int zzz;
}st_foo; // st_foo doesn't have any pointer members
[主机代码]
/* OpenCL initalize... */
st_foo stVar;
cl_mem cm_buffer;
cm_buffer = clCreateBuffer(cxContext, CL_MEM_READ_ONLY, sizeof(st_foo), NULL, NULL);
clSetKernelArg(ckKernel, 0, sizeof(cl_mem), (void*)&cm_buffer);
clEnqueueWriteBuffer(cqueue, cm_buffer, CL_TRUE, 0, sizeof(st_foo), &stVar, 0, NULL, NULL);
[内核代码]
__kernel void testfunction(__global const st_foo *stVar)
{
printf("stVar->aaa=%d\n", stVar->aaa);
}
推荐答案
如果不使用OpenCL数据类型,则在OpenCL中声明结构是不安全的.而且,对齐可能是一个问题,迫使主机/设备编译器中的数据包对齐.
It is not safe to declare structs in OpenCL if you are not using the OpenCL datatypes. And also, alignment may be an issue, force a packet alignment in the Host/Device compiler.
您应将结构声明为:
[主持人]
typedef struct __attribute__ ((packed)) _st_foo
{
cl_int aaa;
cl_int bbb;
.....
cl_int zzz;
}st_foo;
[设备]
typedef struct __attribute__ ((packed)) _st_foo
{
int aaa;
int bbb;
.....
int zzz;
};
另外,如果只需要一个参数而不是结构数组,则只需将其传递为:
Aditionally, if you just want a single parameter, not an array of structs, then just pass it in as:
clSetKernelArg(ckKernel, 0, sizeof(mystruct), mystruct);
这篇关于OpenCL:使用struct作为内核参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!