0

如何在设备中使用主机功能?
例如在下面的函数中,我想返回一个值

__device__ float magnitude2( void ) {
    return r * r + i * i;
}

但是这个功能是一个设备功能,我收到了这个错误:
calling a host function from a __device__/__global__ function is not allowed
解决这个问题的最佳方法是什么?

对代码的额外评论:

我想定义这个结构:

struct cuComplex {
    float   r;
    float   i;
    cuComplex( float a, float b ) : r(a), i(b)  {}
    __device__ float magnitude2( void ) {
        return r * r + i * i;
    }
    __device__ cuComplex operator*(const cuComplex& a) {
        return cuComplex(r*a.r - i*a.i, i*a.r + r*a.i);
    }
    __device__ cuComplex operator+(const cuComplex& a) {
        return cuComplex(r+a.r, i+a.i);
    }
};
4

1 回答 1

2

现在我们知道问题涉及 C++ 结构,答案很明显 - 类的构造函数也必须可用作 __device__ 函数,以便能够在内核中实例化类。在您的示例中,结构应定义如下:

struct cuComplex {
    float   r;
    float   i;

    __device__ __host__
    cuComplex( float a, float b ) : r(a), i(b)  {}

    __device__ 
    float magnitude2( void ) {
        return r * r + i * i;
    }

    __device__ 
    cuComplex operator*(const cuComplex& a) {
        return cuComplex(r*a.r - i*a.i, i*a.r + r*a.i);
    }

    __device__ 
    cuComplex operator+(const cuComplex& a) {
        return cuComplex(r+a.r, i+a.i);
    }
};

您看到的错误是因为每当实例化类时都需要调用构造函数。在您的原始代码中,构造函数仅声明为主机函数,导致编译错误。

于 2012-09-12T07:28:29.380 回答