【问题标题】:Initialize an unsigned char using cudaMemcpy使用 cudaMemcpy 初始化无符号字符
【发布时间】:2019-10-07 00:24:54
【问题描述】:

我使用 cudaMalloc 为 unsigned char 数组分配内存,并使用 cudaMemset 进行初始化。

unsigned char *device_channel_data;
cudaMalloc( device_channel_data, sizeof(unsigned char) * image_size);
cudaMemset( *device_channel_data, 0, sizeof(unsigned char) * image_size);

之后,我通过将数据复制回主机来检查它是否真的设置为 0。我正在打印一些元素来检查数据,但打印的值是随机的。

unsigned char *host_channel_channel;
cudaMemcpy(host_channel_channel, device_channel_data, sizeof(unsigned char) * image_size, cudaMemcpyDeviceToHost);

    for(int i = 0; i < 10; i ++)
    {
        std::cout<< (int)host_channel_channel[i] << std::endl;
    }

我想将 device_channel 数据初始化为 0。 我对指针和 CUDA 编程的知识非常有限。我刚开始使用 CUDA 编程。提前感谢您的帮助。

【问题讨论】:

  • cudaMalloc((void**)&amp;device_channel_data, sizeof(unsigned char) * image_size); cudaMemset(device_channel_data, 0, sizeof(unsigned char) * image_size);

标签: c++ cuda


【解决方案1】:

你的问题的答案在CUDA的文档中:https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__MEMORY.html

对于错误处理 (Use of cudamalloc(). Why the double pointer?),CUDA-API 需要一个指向指针的指针作为分配内存的输入参数,而对于 memset,则需要一个简单的指针。将您的代码更改为:

unsigned char *device_channel_data;
cudaMalloc( (void**)&device_channel_data, sizeof(unsigned char) * image_size);
cudaMemset( device_channel_data, 0, sizeof(unsigned char) * image_size);

一切正常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-20
    • 1970-01-01
    • 1970-01-01
    • 2013-04-29
    • 1970-01-01
    • 2013-11-25
    • 2012-03-03
    相关资源
    最近更新 更多