如何将数据从unsigned int复制到CUDA中的ulong4

时间:2013-11-04 00:39:11

标签: c++ cuda memcpy

.h文件:

#define VECTOR_SIZE 1024   

.cpp文件:

int main ()
{
    unsigned int* A;
    A = new unsigned int [VECTOR_SIZE];

    CopyToDevice (A);
}

.cu文件:

void CopyToDevice (unsigned int *A)
{
    ulong4 *UA
    unsigned int VectorSizeUlong4 = VECTOR_SIZE / 4;
    unsigned int VectorSizeBytesUlong4 = VectorSizeUlong4 * sizeof(ulong4);

    cudaMalloc( (void**)&UA, VectorSizeBytesUlong4 );

    // how to use cudaMemcpy to copy data from A to UA?

    // I tried to do the following but it gave access violation error:
    for (int i=0; i<VectorSizeUlong4; ++i)
    {
        UA[i].x = A[i*4 + 0];
        UA[i].y = A[i*4 + 1];
        UA[i].z = A[i*4 + 2];
        UA[i].w = A[i*4 + 3];
    }
    // I also tried to copy *A to device and then work on it instead going back to CPU to access *A every time but this did not work again
}

enter image description here

2 个答案:

答案 0 :(得分:3)

CUDA ulong4是一个16字节对齐的结构,定义为

struct __builtin_align__(16) ulong4
{
  unsigned long int x, y, z, w;
};

这意味着要用于填充ulong4流的四个连续32位无符号源整数的流大小相同。最简单的解决方案包含在您发布的图像的文本中 - 只是(隐式或显式地)转换unsigned int指向ulong4指针的指针,直接在主机上使用cudaMemcpy设备内存,并将生成的设备指针传递给您需要ulong4输入的任何内核函数。您的设备传输功能可能如下所示:

ulong4* CopyToDevice (unsigned int* A)
{
    ulong4 *UA, *UA_h;
    size_t VectorSizeUlong4 = VECTOR_SIZE / 4;
    size_t VectorSizeBytesUlong4 = VectorSizeUlong4 * sizeof(ulong4);

    cudaMalloc( (void**)&UA, VectorSizeBytesUlong4);
    UA_h = reinterpret_cast<ulong4*>(A); // not necessary but increases transparency
    cudaMemcpy(UA, UA_h, VectorSizeBytesUlong4);

    return UA;   
}

[通常免责声明:用浏览器编写,未经测试或编译,自担风险使用]

答案 1 :(得分:2)

这应该引起所有警钟:

cudaMalloc( (void**)&UA, VectorSizeBytesUlong4 );
// ...
UA[i].x = A[i*4 + 0];

您正在设备上分配UA,然后在主机代码中使用它。不要那样做。您需要使用cudaMemcpy将数组复制到设备。 This tutorial向您展示了一个使用cudaMemcpy复制内容的基本程序。 cudaMemcpy的length参数是数组的长度(以字节为单位)。在你的情况下是VECTOR_SIZE * sizeof(unsigned int)