将cuda设备指针传递给主机功能

时间:2013-03-21 19:10:48

标签: c pointers cuda gpgpu

我有一个我正在研究的程序。我是CUDA和C的新手,所以对我来说真是个颠簸。我正在尝试将结构复制到设备中。然后我试图通过将结构复制到设备来使结构回到主机。以下是代码:

typedef struct {
    int row;
    int col;
    float *arr;
    int numElements;
} Matrix;

Matrix *RMatrix = //definition here

Matrix *d_RMatrix;

    copyMatrix(d_RMatrix, RMatrix, hostToDevice);

    Matrix *check = createMatrix(0, 0, NULL, 0);

    copyMatrix(check, d_RMatrix, deviceToHost);

以及copyMatrix的定义:

void copyMatrix (Matrix *copyTo, Matrix *copyFrom, Copy_type type) 
{

    if(type == hostToDevice) {

        // create temporary host matrix and array
        Matrix *copyFrom_h = createMatrix(copyFrom->row, copyFrom->col, NULL, copyFrom->numElements);

        // allocate device memory, pointing to array in host. Copy array to device memory
        cudaMalloc((void**) &copyFrom_h->arr, sizeof(float) * copyFrom_h->numElements);
        cudaMemcpy(copyFrom_h->arr, copyFrom->arr, sizeof(float) * copyFrom_h->numElements, cudaMemcpyHostToDevice);

        // copy the temporary memory to device
        cudaMalloc((void**) &copyTo, sizeof(Matrix));
        cudaMemcpy(copyTo, copyFrom_h, sizeof(Matrix), cudaMemcpyHostToDevice);

        copyFrom_h = NULL;
        free(copyFrom_h);

    }

    else if(type == deviceToHost) {

        cudaMemcpy(copyTo, copyFrom, sizeof(Matrix), cudaMemcpyDeviceToHost);

        // allocate space for array in the copy to matrix
        copyTo->arr = makeArray(copyTo->col, copyTo->row);
        cudaMemcpy(copyTo->arr, copyFrom->arr, sizeof(float) * copyTo->numElements, cudaMemcpyDeviceToHost);

    }
}

错误表示第一次调用cudaMemcpy时0x3(d_RMatrix的值)的内存访问无效,导致第二次发生段错误。

这里有什么我想念的吗?谢谢你的帮助:)

1 个答案:

答案 0 :(得分:1)

在C中,指针是指向对象的实体(在本例中)。创建指针既不创建对象也不为其分配空间。

您已创建指针Matrix *d_RMatrix;,但它未指向任何有效对象。你很幸运它崩溃了,因为偶然它可以设法将数据实际复制到内存中的一些随机位置。

Matrix TheMatrix();
Matrix *PointerToTheMatrix = &TheMatrix;

或者

Matrix *PointerToTheMatrix = createMatrix(...);//remember you will have to delete it eventually!

功能参数是一种方式。如果在函数内部为copyTo分配内容,则在函数外部将不会显示更改。

/编辑: 我有个主意:

Matrix* CreateMatrixInDevice(Matrix* copyFrom)
{
    Matrix* copyTo = NULL;
    cudaMalloc((void**) &copyTo, sizeof(Matrix));//create outer struct
    cudaMemcpy(copyTo, copyFrom, sizeof(Matrix), cudaMemcpyHostToDevice);//copy data from outer struct
    //the arr element in the device is now INVALID (pointing to host)

    cudaMalloc((void**) &copyTo->arr, sizeof(float) * copyFrom->numElements);//create inner array
    cudaMemcpy(copyTo->arr, copyFrom->arr, sizeof(float) * copyFrom->numElements, cudaMemcpyHostToDevice);//copy matrix data

    return copyTo;
}