2012-01-01 64 views
4

可以使用cudaMemcpy分配与cudaMallocPitch分配的内存吗?如果不是,你能告诉,应该使用哪个函数。 cudaMallocPitch返回线性内存,所以我想应该使用cudaMemcpy。复制由cudaMallocPitch分配的内存

+1

它可以是,但它会通常使用cudaMemcpy2D来复制倾斜的分配。 – talonmies 2012-01-01 23:34:45

+0

cudaMemcpy2D使用dpitch和spitch的语法,但我不确定,当我们从设备复制到主机时,这些值是什么。你能告诉或举一个例子吗?谢谢。 – user1118148 2012-01-02 00:13:06

回答

8

您当然可以使用cudaMemcpy复制倾斜的设备内存,但使用cudaMemcpy2D更为常用。从主机到设备投副本的一个例子是这个样子:

#include "cuda.h" 
#include <assert.h> 

typedef float real; 

int main(void) 
{ 

    cudaFree(0); // Establish context 

    // Host array dimensions 
    const size_t dx = 300, dy = 300; 

    // For the CUDA API width and pitch are specified in bytes 
    size_t width = dx * sizeof(real), height = dy; 

    // Host array allocation 
    real * host = new real[dx * dy]; 
    size_t pitch1 = dx * sizeof(real); 

    // Device array allocation 
    // pitch is determined by the API call 
    real * device; 
    size_t pitch2; 
    assert(cudaMallocPitch((real **)&device, &pitch2, width, height) == cudaSuccess); 

    // Sample memory copy - note source and destination pitches can be different 
    assert(cudaMemcpy2D(device, pitch2, host, pitch1, width, height, cudaMemcpyHostToDevice) == cudaSuccess); 

    // Destroy context 
    assert(cudaDeviceReset() == cudaSuccess); 

    return 0; 
} 

(注:未经测试,cavaet自负和所有.....)

+0

谢谢。它编译好。我添加删除和cudaFree等,并检查,它完成任务。 – user1118148 2012-01-02 14:52:08