2

私はcudaとC ++が初めてで、これを理解できないようです。

私がやりたいことは、2D配列Aをデバイスにコピーしてから、それを同一の配列Bにコピーして戻すことです.

B 配列が A と同じ値を持つことを期待しますが、間違っていることがあります。

CUDA - 4.2、win32 用にコンパイル、64 ビット マシン、NVIDIA Quadro K5000

これがコードです。

void main(){

cout<<"Host main" << endl;

// Host code
const int width = 3;
const int height = 3;
float* devPtr;
float a[width][height]; 

//load and display input array
cout << "a array: "<< endl;
for (int i = 0 ; i < width; i ++)
{
    for (int j = 0 ; j < height; j ++)
    {
        a[i][j] = i + j;
        cout << a[i][j] << " ";

    }
    cout << endl;
}
cout<< endl;


//Allocating Device memory for 2D array using pitch
size_t host_orig_pitch = width * sizeof(float); //host original array pitch in bytes
size_t pitch;// pitch for the device array 

cudaMallocPitch(&devPtr, &pitch, width * sizeof(float), height);

cout << "host_orig_pitch: " << host_orig_pitch << endl;
cout << "sizeof(float): " << sizeof(float)<< endl;
cout << "width: " << width << endl;
cout << "height: " << height << endl;
cout << "pitch:  " << pitch << endl;
cout << endl;

cudaMemcpy2D(devPtr, pitch, a, host_orig_pitch, width, height, cudaMemcpyHostToDevice);

float b[width][height];
//load b and display array
cout << "b array: "<< endl;
for (int i = 0 ; i < width; i ++)
{
    for (int j = 0 ; j < height; j ++)
    {
        b[i][j] = 0;
        cout << b[i][j] << " ";
    }
    cout << endl;
}
cout<< endl;


//MyKernel<<<100, 512>>>(devPtr, pitch, width, height);
//cudaThreadSynchronize();


//cudaMemcpy2d(dst, dPitch,src ,sPitch, width, height, typeOfCopy )
cudaMemcpy2D(b, host_orig_pitch, devPtr, pitch, width, height, cudaMemcpyDeviceToHost);


// should be filled in with the values of array a.
cout << "returned array" << endl;
for(int i = 0 ; i < width ; i++){
    for (int j = 0 ; j < height ; j++){
        cout<< b[i][j] << " " ;
    }
    cout<<endl;
}

cout<<endl;
system("pause");

}

これが出力です。

ホスト メイン A アレイ 0 1 2 1 2 3 2 3 4

host_orig_pitch: 12 sizeof(float): 4 幅: 3 高さ: 3 ピッチ: 512

b配列: 0 0 0 0 0 0 0 0 0

返された配列 0 0 0 1.17549e-038 0 0 0 0 0

何かキーを押すと続行します 。. .

さらに情報が必要な場合はお知らせください。投稿します。

どんな助けでも大歓迎です。

4

1 に答える 1

5

コメントで特定されているように、元の投稿者はcudaMemcpy2D呼び出しに間違った引数を提供していました。転送の幅引数は常にバイト単位であるため、上記のコードでは次のようになります。

cudaMemcpy2D(b, host_orig_pitch, devPtr, pitch, width, height, cudaMemcpyDeviceToHost);

する必要があります

cudaMemcpy2D(b, host_orig_pitch, devPtr, pitch, width * sizeof(float), height, cudaMemcpyDeviceToHost);

この回答は、この質問を未回答リストから外すためにコミュニティ ウィキとして追加されたことに注意してください。

于 2014-05-03T09:11:16.610 に答える