如何使用cudaMalloc/cudaMemcpy作为指向包含指针的结构的指针?

t_c*_*arn 0 pointers cuda

我看过这个网站和其他人,并没有任何效果.我正在为我的具体案例提出问题.

我有一堆矩阵,目标是使用内核让GPU对所有矩阵执行相同的操作.我很确定我可以让内核工作,但我不能让cudaMalloc/cudaMemcpy工作.

我有一个指向Matrix结构的指针,它有一个名为elements的成员,指向一些浮点数.我可以做所有非cuda mallocs就好了.

感谢您的帮助.

码:

typedef struct {
    int width;
    int height;
    float* elements;
} Matrix;

int main void() {
    int rows, cols, numMat = 2; // These are actually determined at run-time
    Matrix* data = (Matrix*)malloc(numMat * sizeof(Matrix));

    // ... Successfully read from file into "data" ...

    Matrix* d_data;
    cudaMalloc(&d_data, numMat*sizeof(Matrix)); 
    for (int i=0; i<numMat; i++){
        // The next line doesn't work
        cudaMalloc(&(d_data[i].elements), rows*cols*sizeof(float));

        // Don't know if this works
        cudaMemcpy(d_data[i].elements, data[i].elements,  rows*cols*sizeof(float)), cudaMemcpyHostToDevice);
    }

    // ... Do other things ...
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

Mic*_*idl 5

你必须要知道你的记忆所在.malloc分配主机内存,cudaMalloc在设备上分配内存并返回指向该内存的指针.但是,此指针仅在设备功能中有效.

您想要的是如下所示:

typedef struct {
    int width;
    int height;
    float* elements;
} Matrix;

int main void() {
    int rows, cols, numMat = 2; // These are actually determined at run-time
    Matrix* data = (Matrix*)malloc(numMat * sizeof(Matrix));

    // ... Successfully read from file into "data" ...
    Matrix* h_data = (Matrix*)malloc(numMat * sizeof(Matrix));
    memcpy(h_data, data, numMat * sizeof(Matrix);

    for (int i=0; i<numMat; i++){

        cudaMalloc(&(h_data[i].elements), rows*cols*sizeof(float));
        cudaMemcpy(h_data[i].elements, data[i].elements,  rows*cols*sizeof(float)), cudaMemcpyHostToDevice);

     }// matrix data is now on the gpu, now copy the "meta" data to gpu
     Matrix* d_data;
     cudaMalloc(&d_data, numMat*sizeof(Matrix)); 
     cudaMemcpy(d_data, h_data, numMat*sizeof(Matrix));
     // ... Do other things ...
}
Run Code Online (Sandbox Code Playgroud)

要明确: Matrix* data包含主机上的数据. Matrix* h_data包含指向元素中设备内存的指针,这些元素可以作为参数传递给内核.内存在GPU上. Matrix* d_data完全在GPU上,可以像主机上的数据一样使用.

在您的内核代码中,您现在可以访问矩阵值,例如,

__global__ void doThings(Matrix* matrices)
{
      matrices[i].elements[0] = 42;
}
Run Code Online (Sandbox Code Playgroud)