我正在开发一个程序。我是 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**) ©From_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**) ©To, 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 的值)处的内存访问无效,并导致第二次出现段错误。
我这里有什么遗漏的吗?感谢您的帮助:)
最佳答案
在 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**) ©To, 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**) ©To->arr, sizeof(float) * copyFrom->numElements);//create inner array
cudaMemcpy(copyTo->arr, copyFrom->arr, sizeof(float) * copyFrom->numElements, cudaMemcpyHostToDevice);//copy matrix data
return copyTo;
}
关于c - 将 cuda 设备指针传递给主机函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15556133/