为什么我得到__device __,__ conststant __,__ shared__不支持动态初始化?

BRa*_*t27 4 cuda cmake

我不明白为什么dynamic initialization is not supported for __device__, __constant__, __shared__ variables在编译代码时出现错误.我的代码看起来像

wrapper.cu

#include "../Params.hpp"

__constant__ Params cparams;

void wrapperFunction(uint& a)
{
   Params ab;
   a = 20;
}
Run Code Online (Sandbox Code Playgroud)

Params.hpp

#include "Utils.hpp"

typedef struct Params
{
   vectorTypef a;
} Params;
Run Code Online (Sandbox Code Playgroud)

Utils.hpp

#include "Vec2.hpp"

typedef unsigned int uint;
typedef Vec2<float> vectorTypef;
Run Code Online (Sandbox Code Playgroud)

Vec2.hpp

template <typename T>
class Vec2
{
public:
   Vec2(){ x = 0.0; y = 0.0;}
   T x, y;
};
Run Code Online (Sandbox Code Playgroud)

使用命令构建cmake

CUDA_ADD_EXECUTABLE(test main.cpp cudasrc/wrapper.cu

Rob*_*lla 11

您的Params结构用在__constant__内存定义中cparams.

您的Paramsstruct包含一个a类型的元素,vectorTypef它是Vec2类的typedef float.这个类有一个默认的构造函数,它最终分配了Paramsstruct的元素.这种将数据分配给__constant__区域的方法在设备代码或主机代码中都是不合法的.

在设备代码中,完全修改__constant__值是不合法的.在主机代码中(这里是视图中的内容),__constant__应使用适当的API分配值,即cudaMemcpyToSymbol.我建议您明确地在主机代码中分配这些,而不是通过构造函数.

因此,解决此问题的一种可能方法是将默认构造函数更改为空构造函数:

public:
   __host__ __device__ Vec2(){ }; // change this line
   T x, y;
Run Code Online (Sandbox Code Playgroud)

(你也可以删除空的默认构造函数行)

并且,在wrapper.cu(可能在wrapperFunction)中,初始化你的Params __constant__结构:

Params hparams;
hparams.a.x = 0.0;
hparams.a.y = 0.0;
cudaMemcpyToSymbol(cparams, &hparams, sizeof(Params));
Run Code Online (Sandbox Code Playgroud)