我有一个很简单的问题,但我不明白。我正在使用4.2 cuda。

我有以下代码:

在我的cudaClass.h中:

unsigned char *dev_trimapExpanded;

在我的cudaClass.cpp中:
void cudaClass::expansionTrimap() {
    printf("dev_trimapExpanded %d before function \n", dev_trimapExpanded);
    //Call cuda function
    cudaError_t cudaStatus = expansionTrimapCuda(dev_trimapExpanded, width, height);
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "expansionTrimapCuda failed!\n");
    }

    printf("dev_trimapExpanded %d after function \n", dev_trimapExpanded);
}

在我的文件kernel.cu中,我有:
cudaError_t expansionTrimapCuda(unsigned char *dev_trimapExpanded, size_t width, size_t height)
{
    size_t size = width*height;

    cudaError_t cudaStatus;

    // Choose which GPU to run on, change this on a multi-GPU system.
    cudaStatus = cudaSetDevice(0);
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaSetDevice failed!  Do you have a CUDA-capable GPU installed?");
        return cudaStatus;
    }

    printf("dev_trimapExpanded %d before cudaMalloc \n", dev_trimapExpanded);
    cudaStatus = cudaMalloc((void**)&dev_trimapExpanded, size);
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaMalloc dev_trimapExpanded failed!");
        return cudaStatus;
    }
    printf("dev_trimapExpanded %d after cudaMalloc \n", dev_trimapExpanded);

    return cudaStatus;
}

输出为:
dev_trimapExpanded 0 before function
dev_trimapExpanded 0 before cudaMalloc
dev_trimapExpanded 93323264 after cudaMalloc
dev_trimapExpanded 0 after function

我的指针的地址在cudaMalloc调用之前是0,这是正常的,但是我不明白为什么在函数之后地址是0。指针dev_trimapExpanded的地址不应更改。 cudaMalloc的作用域仅在函数中吗?内存也不是免费的。如何跟踪不同内核调用之间的全局内存?

最佳答案

这种行为是绝对正确的,您的问题是,在调用函数时,您是按“按值”传递指针,而不是按“按引用”传递指针。所以现在发生的是,当函数被称为youre指针被复制时,副本的值在函数内部被更改,但是当函数完成后,旧指针完全不受影响(因为所有更改仅发生在副本)。

尝试使用此方法代替函数头:

cudaError_t expansionTrimapCuda(unsigned char *& dev_trimapExpanded, ... )

另请参阅:Pointer to Pointer / Reference to Pointer

关于c++ - cuda内存分配cudaMalloc,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12738711/

10-11 03:24