如何将指向设备函数的指针作为内核函数的参数传递?

取消

这个问题是关于CUDA C / C ++编程的。我尝试了很多搜索,但是没有找到合适的问题,因此也没有回答。
我有1个设备功能,1个内核功能和主要功能:

typedef float (*pfunc)(float arg);

__device__ float dev_func(float arg) {
    return arg * arg;
}

__global__ void ker_func(pfunc fnc) {
    printf("%f\n", fnc(2));
}

int main(void) {
    pfunc fnc = dev_func;
    //now how do I copy this pointer to device memory?
    ker_func<<<1,1>>>(...);
    return 0;
}
辛达罗德

CUDA编程指南中

__global__主机代码中使用功能的地址不能在设备代码中使用(例如,启动内核)。同样,__global__设备代码中使用功能的地址不能在主机代码中使用。

不允许使用__device__主机代码中的函数地址

因此,您有两种选择

__device__全局定义函数指针,然后在内核中调用它。

typedef float (*pfunc)(float arg);

__device__ float dev_func(float arg) {
    return arg * arg;
}

// create device function pointer here
__device__ pfunc dev_func_ptr = dev_func;

__global__ void ker_func() {
    // call function through device function pointer
    printf("%f\n", dev_func_ptr(2));
}

如果要将函数指针传递给内核作为参数,则:

#define gpuErrchk(val) \
    cudaErrorCheck(val, __FILE__, __LINE__, true)
void cudaErrorCheck(cudaError_t err, char* file, int line, bool abort)
{
    if(err != cudaSuccess)
    {
        printf("%s %s %d\n", cudaGetErrorString(err), file, line);
        if(abort) exit(-1);
    }
}

typedef float (*pfunc)(float arg);

__device__ float dev_func(float arg) {
    return arg * arg;
}

// create device function pointer here
__device__ pfunc dev_func_ptr = dev_func;

__global__ void ker_func(pfunc fnc) {
    // call function through device function pointer
    printf("%f\n", fnc(2));
}


int main(int argc, char** argv)
{
    // create a host function pointer
    pfunc host_function_ptr;
    // copy function pointer value from device to host
    gpuErrchk(cudaMemcpyFromSymbol(&host_function_ptr, dev_func_ptr, sizeof(pfunc)));
    // pass the copied function pointer in kernel
    ker_func<<<1,1>>>(host_function_ptr);

    gpuErrchk(cudaPeekAtLastError());
    gpuErrchk(cudaDeviceSynchronize());

    return 0;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何将函数指针作为类模板参数传递?

将指向类方法的指针作为函数参数传递

c - 如何将参数作为指向数组的指针传递

如何将函数作为参数传递

如何将指向动态分配数组的指针作为函数参数进行传输

如何将 lamda 作为成员函数的函数指针参数传递?

如何将指向结构的指针传递给构造函数?

如何将指针传递给在 C++ 中作为引用传递参数的函数

如何将函数作为参数传递给transform()函数?

如何将分布函数作为函数的参数传递?

Python,如何将参数传递给函数指针参数?

如何将指针/数组作为参数传递给 GTK 回调函数?

如何访问作为指向指针参数的指针传递给函数的结构成员?

将指针作为函数参数传递

将双指针作为函数参数传递

如何将函数作为参数传递给参数?

如何将 cstring 作为函数参数/参数传递

这个构造函数代码如何将指针作为参数?

如何将参数传递给C中的函数指针?

使用指向成员的指针将成员函数作为参数传递

在Python中将“指向虚拟函数的指针”作为参数传递

使用指向作为函数参数传递的数组的指针

如果传递的函数也将函数作为参数,如何将函数作为参数传递给C中的函数?

使用 C++11 将指向成员函数的指针作为参数传递

将指向任何成员函数的指针作为类模板参数传递

将指向2D VLA的指针作为函数参数传递给C中的行向量

将指向字符串的指针作为函数的参数传递时发生类型冲突

如何将多个列表值作为函数参数传递?

如何将字典作为函数参数传递?