复制使用cudamallocHost分配的内存部分

复制使用cudamallocHost分配的内存部分,cuda,gpu,nvidia,gpgpu,Cuda,Gpu,Nvidia,Gpgpu,我想将阵列的一部分从主机上的固定内存复制到CUDA设备。例如,我已经分配了大小为500的固定内存,我想将元素100-399复制到设备上大小为300的数组中 这是我的密码 int main() { const unsigned int N = 500; const unsigned int bytes = N * sizeof(int); cudaError_t status = cudaSuccess; int *h_a; int *d_a;

我想将阵列的一部分从主机上的固定内存复制到CUDA设备。例如,我已经分配了大小为500的固定内存,我想将元素100-399复制到设备上大小为300的数组中

这是我的密码

int main()
{
    const unsigned int N = 500;
    const unsigned int bytes = N * sizeof(int);
    cudaError_t status = cudaSuccess;

    int *h_a;
    int *d_a;

    status = cudaMallocHost((void**) &h_a, bytes);
    if (status != cudaSuccess)
        cout << "Error allocating pinned host memory\n";

    status = cudaMalloc((void**) &d_a, bytes);
    if (status != cudaSuccess)
        cout << "Error allocating pinned device memory\n";

    for (int i = 0; i < N; i++) {
        h_a[i] = i;
    }

    status = cudaMemcpy(d_a, h_a + 100, bytes - (200 * sizeof(int)), cudaMemcpyHostToDevice);
    if (status != cudaSuccess)
        cout << "Error copying to device: " << cudaGetErrorString(status) << "\n";
    cudaMemcpy(h_a + 100, d_a, bytes - (200 * sizeof(int)), cudaMemcpyDeviceToHost);
    if (status != cudaSuccess)
        cout << "Error copying to host: " << cudaGetErrorString(status) << "\n";       


    cudaFree(d_a);
    cudaFreeHost(h_a);

    return 0;
}

只有主机到设备的复制失败。设备到主机的复制工作正常。同样,如果我使用非固定主机内存,同样的代码也可以正常工作。有没有办法使用固定内存实现这一点?

上述代码实际上可以正确编译和运行。也许我在测试时使用了一个旧的可执行文件。

您发布的代码没有问题,它为我运行时没有任何运行时错误。是的,确实如此。对不起,浪费了你的时间。可能,我正在运行另一个使用旧代码的可执行文件。请记住几天后回来接受您的答案,这样这个问题就从未回答的问题列表中消失了。
Error copying to device: invalid argument