如何在OpenCL中的内核函数中声明一个函数?

Se *_*orm 4 c indexing opencl

我想在内核函数中定义一个函数,使我的索引代码更清晰:

kernel void do_something (const int some_offset,
                          const int other_offset,
                          global float* buffer)
{
    int index(int x, int y)
    {
        return some_offset+other_offset*x+y;
    }

    float value = buffer[index(1,2)];
    ...
}
Run Code Online (Sandbox Code Playgroud)

否则我必须在我的内核和索引之外声明索引函数

float value = buffer[index(1,2,some_offset,other_offset)];
Run Code Online (Sandbox Code Playgroud)

这将使它更丑陋等.有什么办法可以做到这一点?编译器给我一个错误,说:

OpenCL Compile Error: clBuildProgram failed (CL_BUILD_PROGRAM_FAILURE).
Line 5: error: expected a ";"
Run Code Online (Sandbox Code Playgroud)

是否有可能做我想要的或有不同的方法来实现同样的目标?谢谢!

zvr*_*rba 5

C不支持嵌套函数.但是,您的案例很简单,可以使用宏实现:

#define index(x,y) some_offset+other_offset*(x)+(y)
Run Code Online (Sandbox Code Playgroud)

围绕x和y的括号对于使宏执行你想要的更为复杂的表达式是至关重要的,例如,index(a+b,c).

  • 你还应该将parens放在整个表达式周围:`(some_offset + other_offset*(x)+(y))`.否则`index(x,y)*2`会令人惊讶. (3认同)