调用cudaMemcpy2DToArray时访问违规读取位置

Access violation reading location when calling cudaMemcpy2DToArray

我在设备中分配了一个二维数组,想将一个二维浮点数组复制到设备中。 ImgSrc 是 OpenCV 中的 Mat 类型,我通过使用 cudaMemcpy2DToArray() 将它的元素复制到名为 ImgSrc_f.then 的二维浮点数组中,我将主机二维数组 (ImgSrc_f) 复制到设备二维数组 Src。 二维数组的大小是 512X512.

cudaChannelFormatDesc floattex = cudaCreateChannelDesc<float>();
cudaArray *Src;
cudaMallocArray(&Src, &floattex, 512, 512);

float *ImgSrc_f[512];
for (int i=0; i<512; i++)
         ImgSrc_f[i] = (float *)malloc(512 * sizeof(float));
for(int i=0;i<512;i++)
    for(int j=0;j<512;j++)
    {
        ImgSrc_f[i][j]=ImgSrc.at<float>(i,j);
    }
//copy from host memory to device
cudaMemcpy2DToArray(Src, 0, 0,ImgSrc_f,512 * sizeof(float),512 *sizeof(float), 512,cudaMemcpyHostToDevice);

但我遇到了这个异常:

Access violation reading location 0x0000000000281000

ImgSrc_f 不指向连续的 512x512 内存块。尝试改变

float *ImgSrc_f[512];
for (int i=0; i<512; i++)
         ImgSrc_f[i] = (float *)malloc(512 * sizeof(float));
for(int i=0;i<512;i++)
    for(int j=0;j<512;j++)
    {
        ImgSrc_f[i][j]=ImgSrc.at<float>(i,j);
    }

类似于

float *ImgSrc_f;
ImgSrc_f = (float *)malloc(512 * 512 * sizeof(float));
for(int i=0;i<512;i++)
    for(int j=0;j<512;j++)
    {
        ImgSrc_f[i * 512 + j]=ImgSrc.at<float>(i,j);
    }

cudaMemcpy2DToArray expects 指向单个连续内存块的源指针。