OpenCL-是否可以从内核中调用另一个函数?

OpenCL-是否可以从内核中调用另一个函数?,opencl,Opencl,以下是我在这里提供的教程: 他们列出的内核是这样的,它计算两个数字的总和并将其存储在输出变量中: __kernel void vector_add_gpu (__global const float* src_a, __global const float* src_b, __global float* res, const int num) { /* get_global_id(0)

以下是我在这里提供的教程:

他们列出的内核是这样的,它计算两个数字的总和并将其存储在输出变量中:

__kernel void vector_add_gpu (__global const float* src_a,
                     __global const float* src_b,
                     __global float* res,
           const int num)
{
   /* get_global_id(0) returns the ID of the thread in execution.
   As many threads are launched at the same time, executing the same kernel,
   each one will receive a different ID, and consequently perform a different computation.*/
   const int idx = get_global_id(0);

   /* Now each work-item asks itself: "is my ID inside the vector's range?"
   If the answer is YES, the work-item performs the corresponding computation*/
   if (idx < num)
      res[idx] = src_a[idx] + src_b[idx];
}
\uuuu内核无效向量\uu添加\uu gpu(\uuuu全局常量浮点*src\uA,
__全局常量浮点*src_b,
__全球浮动*res,
常数(整数)
{
/*get_global_id(0)返回正在执行的线程的id。
由于同时启动多个线程,执行同一内核,
每一个将接收不同的ID,并因此执行不同的计算*/
const int idx=获取全局id(0);
/*现在每个工作项都会问自己:“我的ID是否在向量的范围内?”
如果答案为“是”,则工作项将执行相应的计算*/
if(idx
1) 比如说,所执行的操作比求和要复杂得多——这证明了其自身的功能。让我们称之为ComplexOp(in1,in2,out)。我如何实现这个函数,使vector_add_gpu()能够调用并使用它?你能给出示例代码吗


2) 现在让我们把这个例子发挥到极致,我现在想调用一个对这两个数字进行运算的通用函数。如何设置它,以便向内核传递指向此函数的指针,并根据需要调用它?

您可以在内核中使用辅助函数,请参阅。您不能将函数指针传递到内核。

是的,这是可能的。您只需记住OpenCL是基于C99的,但有一些警告。您可以在同一内核文件内或在单独的文件中创建其他函数,并且只需在开始时包含它。辅助函数不需要声明为内联函数,但是请记住,调用时OpenCL将内联函数。在调用辅助函数时,指针也不可用

范例

float4 hit(float4 ray_p0, float4 ray_p1, float4 tri_v1, float4 tri_v2, float4 tri_v3)
{
//logic to detect if the ray intersects a triangle
}

__kernel void detection(__global float4* trilist, float4 ray_p0, float4 ray_p1)
{
int gid = get_global_id(0);
float4 hitlocation = hit(ray_p0, ray_p1, trilist[3*gid], trilist[3*gid+1], trilist[3*gid+2]);
}

我喜欢你的名字也是Adam Sw你说的“指针在调用辅助函数时也不可用”是什么意思?在opencl内核中指针不能在内核中的任何地方使用,也不能在从内核调用函数时使用。指针是这些警告之一。不需要指针传递的一个原因是函数始终是内联的,而不是传递到单独的内存地址。只是注释。这是OpenCL,不是CUDA。您不必使用工作组大小的倍数。我经常看到千个丑陋的“如果(idx