检索3d列阵的Cuda

时间:2012-08-09 00:16:42

标签: arrays 3d cuda

我无法弄清楚如何从GPU中检索3D阵列。 我想在主机代码中为3d数组分配内存,调用内核,然后填充数组,然后将主机代码中的3D数组检索到mexFunction中的返回变量(主机代码)。

我已经多次尝试过,这是我的最新代码。结果都是'0',它们应该是'7'。谁能告诉我哪里出错了?它可能与3D参数有关,我不认为我完全理解那部分。

simulate3DArrays.cpp

/* Device code */
__global__ void simulate3DArrays(cudaPitchedPtr devPitchedPtr, 
                             int width, 
                             int height, 
                             int depth) 
{
int threadId;
threadId = (blockIdx.x * blockDim.x) + threadIdx.x;

size_t pitch = devPitchedPtr.pitch; 

for (int widthIndex = 0; widthIndex < width; widthIndex++) {
    for (int heightIndex = 0; heightIndex < height; heightIndex++) {

        *((double*)(((char*)devPitchedPtr.ptr + threadId * pitch * height) + heightIndex * pitch) + widthIndex) = 7.0;

    }
}    
}

mexFunction.cu

/* Host code */
#include <stdio.h>
#include "mex.h"

/* Kernel function */
#include "simulate3DArrays.cpp"

/* Define some constants. */
#define width  5
#define height 9
#define depth  6

void displayMemoryAvailability(mxArray **MatlabMemory);

void mexFunction(int        nlhs,
             mxArray    *plhs[],
             int        nrhs,
             mxArray    *prhs[])
{

double *output;
mwSize ndim3 = 3;
mwSize dims3[] = {height, width, depth};

plhs[0] = mxCreateNumericArray(ndim3, dims3, mxDOUBLE_CLASS, mxREAL);
output = mxGetPr(plhs[0]);

cudaExtent extent = make_cudaExtent(width * sizeof(double), height, depth);
cudaPitchedPtr devicePointer;
cudaMalloc3D(&devicePointer, extent);


simulate3DArrays<<<1,depth>>>(devicePointer, width, height, depth);

cudaMemcpy3DParms deviceOuput = { 0 };
deviceOuput.srcPtr.ptr = devicePointer.ptr;
deviceOuput.srcPtr.pitch = devicePointer.pitch;
deviceOuput.srcPtr.xsize = width;
deviceOuput.srcPtr.ysize = height;

deviceOuput.dstPtr.ptr = output;
deviceOuput.dstPtr.pitch = devicePointer.pitch;
deviceOuput.dstPtr.xsize = width;
deviceOuput.dstPtr.ysize = height;

deviceOuput.kind = cudaMemcpyDeviceToHost;
/* copy 3d array back to 'ouput' */
cudaMemcpy3D(&deviceOuput);


return;
} /* End Mexfunction */

1 个答案:

答案 0 :(得分:1)

基本问题似乎是您指示cudaMemcpy3D复制零字节,因为您没有包含非零范围,该范围定义了传输到API的大小。

您的转移可能很简单:

cudaMemcpy3DParms deviceOuput = { 0 };
deviceOuput.srcPtr = devicePointer;
deviceOuput.dstPtr.ptr = output;
deviceOuput.extent = extent;

cudaMemcpy3D(&deviceOuput);

我无法评论您使用的MEX接口是否正确,但内核看起来是否正确,我没有看到任何其他明显错误的内容,无需转到编译器并尝试运行使用Matlab的代码,我不能。