2012-01-01 28 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