Converting Thrust device iterators to raw pointers

帅比萌擦擦* 提交于 2020-12-25 04:34:51

问题


I'm considering the following simple code in which I'm converting thrust::host_vector<int>::iterator h_temp_iterator = h_temp.begin(); and thrust::device_vector<int>::iterator d_temp_iterator = d_temp.begin(); to raw pointers.

To this end, I'm passing &(h_temp_iterator[0]) and &(d_temp_iterator[0]) to a function and a kernel, respectively. The former (CPU case) compiles, the latter (GPU case) not. The two cases should be in principle symmetric, so I do not understand the reason for the error message which is:

Error   1   error : no suitable conversion function from "thrust::device_ptr<int>" to "int *" exists    

The configurations are:

  1. Windows 7, Visual Studio 2010, CUDA 7.5, compiling for the 3.5 architecture.
  2. Windows 10, Visual Studio 2013, CUDA 8.0, compiling for the 5.2 architecture.

CODE

#include <thrust\host_vector.h>
#include <thrust\device_vector.h>

__global__ void testKernel(int *a, const int N)
{
    int i = threadIdx.x;

    if (i >= N) return;

    a[i] = 2;
}

void testFunction(int *a, const int N)
{
    for (int i = 0; i < N; i++) a[i] = 2;
}

int main()
{
    const int N = 10;

    thrust::host_vector<int> h_temp(N);
    thrust::device_vector<int> d_temp(N);

    thrust::host_vector<int>::iterator h_temp_iterator = h_temp.begin();
    thrust::device_vector<int>::iterator d_temp_iterator = d_temp.begin();

    testFunction(&(h_temp_iterator[0]), N);
    testKernel<<<1, N>>>(&(d_temp_iterator[0]), N);

    for (int i = 0; i < N; i++) printf("%i %i\n", i, h_temp[i]);

    return 0;
}

回答1:


Following talonmies' comments, the solution is to pass

thrust::raw_pointer_cast(&d_temp_iterator[0])

and not

&d_temp_iterator[0]

In the following, the fully working code

#include <thrust\host_vector.h>
#include <thrust\device_vector.h>

__global__ void testKernel(int *a, const int N)
{
    int i = threadIdx.x;

    if (i >= N) return;

    a[i] = 2;

    printf("GPU %i %i\n", i, a[i]);
}

void testFunction(int *a, const int N)
{
    for (int i = 0; i < N; i++) {
        a[i] = 2;
        printf("CPU %i %i\n", i, a[i]);
    }
}

int main()
{
    const int N = 10;

    thrust::host_vector<int> h_temp(N);
    thrust::device_vector<int> d_temp(N);

    thrust::host_vector<int>::iterator h_temp_iterator = h_temp.begin();
    thrust::device_vector<int>::iterator d_temp_iterator = d_temp.begin();

    int *temp = thrust::raw_pointer_cast(&d_temp_iterator[0]);

    testFunction(&(h_temp_iterator[0]), N);
    testKernel<<<1, N>>>(temp, N);

    return 0;
}



回答2:


As you are using thrust, another prettier solution is to get the pointer with data() and cast it to a raw pointer:

thrust::raw_pointer_cast(d_temp_iterator.data())


来源:https://stackoverflow.com/questions/45350747/converting-thrust-device-iterators-to-raw-pointers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!