本文介绍了设备函数指针作为结构成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个(有效的)CPU代码:

I have this (working) CPU code:

#define NF 3
int ND;

typedef double (*POT)(double x, double y);

typedef struct {
    POT pot[NF];
} DATAMPOT;

DATAMPOT *datampot;

double func0(double x, double y);
double func1(double x, double y);
double func2(double x, double y);


int main(void)
{
    int i;

    ND=5;
    datampot=(DATAMPOT *)malloc(ND*sizeof(DATAMPOT));

    for(i=0;i<ND;i++){
        datampot[i].pot[0]=func0;
        datampot[i].pot[1]=func1;
        datampot[i].pot[2]=func2;
    }

    return 0;
}

现在我尝试这样的GPU版本

Now I try a GPU version like this

#define NF 3
int ND;

typedef double (*POT)(double x, double y);

typedef struct {
    POT pot[NF];
} DATAMPOT;

DATAMPOT *dev_datampot;

__device__ double z_func0(double x, double y);
__device__ double z_func1(double x, double y);
__device__ double z_func2(double x, double y);

__global__ void assign(DATAMPOT *dmp, int n)
{
    int i;

    for(i=0;i<n;i++){
        (dmp+i)->pot[0]=z_func0;
        (dmp+i)->pot[1]=z_func1;
        (dmp+i)->pot[2]=z_func2;
    }

}

int main(void)
{
    int i;

    ND=5;
    cudaMalloc((void**)&dev_datampot,ND*sizeof(DATAMPOT));

    assign<<<1,1>>>(dev_datampot,ND);

    return 0;
}

但设备功能指针的分配不起作用。
错误在哪里?以及如何纠正?
非常感谢。
Michele

but the assignment of device function pointers does not work.Where is the mistake? And how it can be corrected?Thanks you very much in advance.Michele

推荐答案

希望这对某人有帮助

#define NF 3
int ND;

typedef double (*POT)(double x, double y);

typedef struct {
    POT pot[NF];
} DATAMPOT;

DATAMPOT *dev_datampot;

__device__ double z_func0(double x, double y);
__device__ double z_func1(double x, double y);
__device__ double z_func2(double x, double y);

//Static pointers to the above device functions    
__device__ POT z_func0_pointer=z_func0;  
__device__ POT z_func1_pointer=z_func1;
__device__ POT z_func2_pointer=z_func2;



int main(void)
{
    int i;
    POT pot_pointer;

    ND=5;
    cudaMalloc((void**)&dev_datampot,ND*sizeof(DATAMPOT));

    for(i=0;i<ND;++i){  
     cudaMemcpyFromSymbol( &pot_pointer,z_func0_pointer, sizeof( POT ) );
  cudaMemcpy(&dev_datampot[i].pot[0]),&pot_pointer,sizeof(POT),cudaMemcpyHostToDevice);

     cudaMemcpyFromSymbol( &pot_pointer,z_func1_pointer, sizeof( POT ) );
  cudaMemcpy(&dev_datampot[i].pot[1]),&pot_pointer,sizeof(POT),cudaMemcpyHostToDevice);

     cudaMemcpyFromSymbol( &pot_pointer,z_func2_pointer, sizeof( POT ) );
  cudaMemcpy(&dev_datampot[i].pot[2]),&pot_pointer,sizeof(POT),cudaMemcpyHostToDevice);
    }

    return 0;
}

这篇关于设备函数指针作为结构成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 02:02