c - 将包含 vector 的结构传递给 CUDA 内核

标签 c struct cuda

我有一个很大的代码,我需要将一个结构传递给一个 CUDA 内核,该内核具有大量用于参数和 vector 的整数。我不知道如何将结构传递给 CUDA 内核。我已经将它复制到设备上,但在尝试编译时出现以下错误:

test_gpu.cpp:63:17: error: invalid operands to binary expression ('void (*)(Test)' and 'dim3')
    computeTotal<<dimGrid, dimBlock>>(test_Device);
test_gpu.cpp:63:36: error: invalid operands to binary expression ('dim3' and 'Test *')
    computeTotal<<dimGrid, dimBlock>>(test_Device);

附件是代码的一个几乎可以工作的小例子,有什么想法吗?

#include <stdio.h>
#include <stdlib.h>
#include <cuda_runtime_api.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <device_functions.h>
#include <device_launch_parameters.h>
#include <vector>
#include <string>

typedef struct Test{
    int x;
    int y;
    int z;
    std::vector<int> vector;
    std::string string;
}Test;

Test test;

__device__ void addvector(Test test, int i){
    test.x += test.vector[i];
    test.y += test.vector[i+1];
    test.z += test.vector[i+2];
}

__global__ void computeTotal(Test test){
    for (int tID = threadIdx.x; tID < threadIdx.x; ++tID )
    addvector(test, tID);
}

int main()
{
    Test test_Host;
    int vector_size = 512;
    test_Host.x = test_Host.y = test_Host.z = 0;
    for (int i=0; i < vector_size; ++i)
    {
        test_Host.vector.push_back(rand());
    }

    Test* test_Device;
    int size = sizeof(test_Host);
    cudaMalloc((void**)&test_Device, size);
    cudaMemcpy(test_Device, &test_Host, size, cudaMemcpyHostToDevice);

    dim3 dimBlock(16);

    dim3 dimGrid(1);

    computeTotal<<dimGrid, dimBlock>>(test_Device);


    return 0;
}

最佳答案

C++ 标准库中的项目通常/通常不能用于 CUDA 设备代码。对此的文档支持是 here .

对于这种特殊情况,这意味着您可能在使用 std::vectorstd::string 时遇到问题。一种可能的解决方法是用普通的 C 风格数组替换它们:

#define MAX_VEC_SIZE 512
#define MAX_STR_SIZE 512

typedef struct Test{
    int x;
    int y;
    int z;
    int vec[MAX_VEC_SIZE];
    char str[MAX_STR_SIZE];
}Test;

这当然需要更改代码中的其他地方。

关于c - 将包含 vector 的结构传递给 CUDA 内核,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47891792/

相关文章:

c - 便携性问题

cuda - CUDA 和其他 OptiX 组件中固有的射线三角形相交

c++ - CUDA:请帮我找出代码中的错误

c# - 如何从 DLL 设置委托(delegate)/回调(C 和 C# 之间的互操作)

C - 为什么当我编译时它无法识别源文件(.c)?

c - 自由(): invalid next size (fast) string too long?

c - memcpy() 和 memmove() 未按预期工作

c++ - 进行调试日志记录的更好方法?

c - 将非 pod 结构插入 GHashTable

performance - 中断开销与控制标志