具有CUDA设备功能的函数指针 我想在CUDA C++代码中使用函数指针,如下面,

具有CUDA设备功能的函数指针 我想在CUDA C++代码中使用函数指针,如下面,,c++,cuda,function-pointers,C++,Cuda,Function Pointers,typedef uuu设备uuuu无效自定义函数常量char*,uint64\u t,char*,常量uint64\u t 这就是我想要的。没有_;装置__;的等价物确实工作得很好 Cuda是否支持函数指针 编辑: 我特别感兴趣的是如何使用设备函数作为指向设备函数的函数指针在设备代码中使用设备函数指针没有什么神奇之处。它在功能和句法上与标准C++完全相同。 例如: #include <cstdio> typedef int (*ufunc)(int args); __device

typedef uuu设备uuuu无效自定义函数常量char*,uint64\u t,char*,常量uint64\u t

这就是我想要的。没有_;装置__;的等价物确实工作得很好

Cuda是否支持函数指针

编辑:


我特别感兴趣的是如何使用设备函数作为指向设备函数的函数指针

在设备代码中使用设备函数指针没有什么神奇之处。它在功能和句法上与标准C++完全相同。 例如:

#include <cstdio>

typedef int (*ufunc)(int args);

__device__ int f1(int x)
{
    int res = 2*x;
    printf("f1 arg = %d, res = %d\n", x, res);
    return res;
}

__device__ int f2(int x, int y, ufunc op)
{
    int res = x + op(y);
    printf("f2 arg = %d, %d, res = %d\n", x, y, res);
    return res;
}


__global__ void kernel(int *z) 
{

    int x = threadIdx.x;
    int y = blockIdx.x;
    int tid = threadIdx.x + blockDim.x * blockIdx.x;

    z[tid] = f2(x, y, &f1);
}

int main()
{
    const int nt = 4, nb = 4;
    int* a_d;
    cudaMalloc(&a_d, sizeof(float) * nt *nb);

    kernel<<<nb, nt>>>(a_d);
    cudaDeviceSynchronize();
    cudaDeviceReset();

    return 0;
}
#include <cstdio>

typedef int (*bfunc)(int args);

__device__ int f1(int x)
{
    int res = 2*x;
    printf("f1 arg = %d, res = %d\n", x, res);
    return res;
}

__device__ int f2(int x, int y, bfunc op)
{
    int res = x + f1(y);
    printf("f2 arg = %d, %d, res = %d\n", x, y, res);
    return res;
}


__global__ void kernel(int *z) 
{

    int x = threadIdx.x;
    int y = blockIdx.x;
    int tid = threadIdx.x + blockDim.x * blockIdx.x;

    z[tid] = f2(x, y, &f1);
}

int main()
{
    const int nt = 4, nb = 4;
    int* a_d;
    cudaMalloc(&a_d, sizeof(float) * nt *nb);

    kernel<<<nb, nt>>>(a_d);
    cudaDeviceSynchronize();
    cudaDeviceReset();

    return 0;
}
这里,我们定义一个指向一元函子的简单指针作为类型,然后定义一个将该类型作为参数的设备函数。内核调用中函数指针的静态赋值在编译时处理,一切正常。如果希望在运行时选择函数指针,则需要遵循已提供的中给出的说明

这里需要记住的重要一点是,在CUDA中,在类型定义中包含CUDA说明符、设备、常量、全局等是不合法的。每个变量实例都有一个说明符作为其定义的一部分

可能重复的