0

以下示例问题:

#include <iostream>

using namespace std;
__device__ __constant__ float* data;

template<class T> void allocOnly(T* deviceDest, size_t numElem)
{
    cudaError_t errCode = cudaMalloc((void**)&deviceDest, numElem*sizeof(T));
    if(errCode != cudaSuccess) 
        cout << "Got error with code " << errCode << endl;
}

int main()
{
    float* test(0);
    allocOnly<float>(test,10);
    cout << "test = " << test << endl;

    float* test2(0);    
    cudaError_t errCode = cudaMalloc((void**)&test2, 10*sizeof(float));
    if(errCode != cudaSuccess) 
        cout << "Got error with code " << errCode << endl;
    cout << "test2 = " << test2 << endl;

    return 0;
}

编译nvcc test.cu -o testBin

返回

test = 0
test2 = 0x310100

为什么通过模板函数调用test时没有修改,cudaMalloc应该修改为指向新分配的设备内存的指针!

4

1 回答 1

3

指针没有被修改,因为cudaMalloc在函数中将allocOnly内存分配给deviceTest函数本地的参数allocOnly。您可以修改函数allocOnly以分配内存,如下所示:

template<class T> void allocOnly(T** deviceDest, size_t numElem)
{
    cudaError_t errCode = cudaMalloc((void**)deviceDest, numElem*sizeof(T));
    if(errCode != cudaSuccess) 
        cout << "Got error with code " << errCode << endl;
}

主函数内部:

int main()
{
    float* test(0);
    allocOnly<float>(&test,10);
    cout << "test = " << test << endl;
    .
    .
    .

}
于 2013-02-05T19:46:05.097 回答