【问题标题】:Overload of operator() for a CUDA matrix classCUDA 矩阵类的 operator() 重载
【发布时间】:2013-07-08 10:20:06
【问题描述】:

我有 CPU 和 GPU (CUDA) 矩阵类,我想重载 operator() 以便我可以读取或写入矩阵的各个元素。

对于 CPU 矩阵类,我可以这样做

OutType & operator()(const int i) { return data_[i]; }

(读取)和

OutType operator()(const int i) const { return data_[i]; }

(写)。对于 GPU 矩阵类,我能够重载 operator() 以供阅读

__host__ OutType operator()(const int i) const { OutType d; CudaSafeCall(cudaMemcpy(&d,data_+i,sizeof(OutType),cudaMemcpyDeviceToHost)); return d; }

但我无法为写作做同样的事情。有人可以提供任何提示来解决这个问题吗?

CPU的写例返回data_[i]的引用,所以赋值工作由构建的C++operator=来执行。我不知道如何为 CUDA 使用相同的机制。

谢谢。

【问题讨论】:

    标签: c++ class cuda operator-overloading


    【解决方案1】:

    您可以创建一个具有重载赋值运算符和类型转换运算符并模拟引用行为的单独类:

    class DeviceReferenceWrapper
    {
    public:
        explicit DeviceReferenceWrapper(void* ptr) : ptr_(ptr) {}
    
        DeviceReferenceWrapper& operator =(int val)
        {
            cudaMemcpy(ptr_, &val, sizeof(int), cudaMemcpyHostToDevice);
            return *this;
        }
    
        operator int() const
        {
            int val;
            cudaMemcpy(&val, ptr_, sizeof(int), cudaMemcpyDeviceToHost);
            return val;
        }
    
    private:
        void* ptr_;
    };
    

    并在矩阵类中使用它

    class Matrix
    {
        DeviceReferenceWrapper operator ()(int i)
        {
            return DeviceReferenceWrapper(data + i);
        }
    };
    

    【讨论】:

    • 非常聪明的解决方案!非常感谢你。只是为了向其他可能感兴趣的用户澄清。此解决方案适用于“阅读”和“写作”情况。再次感谢。
    猜你喜欢
    • 1970-01-01
    • 2010-10-15
    • 2013-02-11
    • 2012-02-07
    • 1970-01-01
    • 2012-04-12
    • 2012-05-04
    • 2016-08-19
    • 1970-01-01
    相关资源
    最近更新 更多