从thrust::device_vector到原始指针再返回
From thrust::device_vector to raw pointer and back?
我明白如何从矢量到原始指针,但我跳过了如何向后走的节拍。
// our host vector
thrust::host_vector<dbl2> hVec;
// pretend we put data in it here
// get a device_vector
thrust::device_vector<dbl2> dVec = hVec;
// get the device ptr
thrust::device_ptr devPtr = &d_vec[0];
// now how do i get back to device_vector?
thrust::device_vector<dbl2> dVec2 = devPtr; // gives error
thrust::device_vector<dbl2> dVec2(devPtr); // gives error
谁能给我举个例子? http://code.google.com/p/thrust/source/browse/examples/cuda/wrap_pointer.cu
Thrust就是一个很好的例子。
#include <thrust/device_ptr.h>
#include <thrust/fill.h>
#include <cuda.h>
int main(void)
{
size_t N = 10;
// obtain raw pointer to device memory
int * raw_ptr;
cudaMalloc((void **) &raw_ptr, N * sizeof(int));
// wrap raw pointer with a device_ptr
thrust::device_ptr<int> dev_ptr = thrust::device_pointer_cast(raw_ptr);
// use device_ptr in Thrust algorithms
thrust::fill(dev_ptr, dev_ptr + N, (int) 0);
// access device memory transparently through device_ptr
dev_ptr[0] = 1;
// free memory
cudaFree(raw_ptr);
return 0;
}
从推力容器中获取原始指针已经由您自己回答了…
dbl2* ptrDVec = thrust::raw_pointer_cast(&d_vec[0]);
初始化和填充推力向量就像标准容器一样,即通过迭代器:
#include <thrust/device_vector.h>
#include <thrust/device_ptr.h>
int main()
{
thrust::device_vector<double> v1(10); // create a vector of size 10
thrust::device_ptr<double> dp = v1.data(); // or &v1[0]
thrust::device_vector<double> v2(v1); // from copy
thrust::device_vector<double> v3(dp, dp + 10); // from iterator range
thrust::device_vector<double> v4(v1.begin(), v1.end()); // from iterator range
}
在您的简单示例中,不需要通过指针绕路,因为您可以直接复制其他容器。一般来说,如果你有一个指向数组开头的指针,如果你提供了数组的大小,你可以使用v3
的版本。
dbl2* ptrDVec = thrust::raw_pointer_cast(&d_vec[0]);有没有办法从这里回到device_vector ?
没有。尽管您应该能够重用初始向量变量
相关文章:
- 从堆栈分配的原始指针构造智能指针
- 将unique_ptr分配给原始指针
- 如何将唯一指针的 std::vector 转换为原始指针的 std::span?
- <Base> <Derived> 具有相同原始指针共享引用的 shared_ptr 和 shared_ptr 实例是否计数?
- C++原始指针和"delete"
- 为什么 C++ 地址中的矢量无法通过原始指针访问
- 如何正确实现具有原始指针的类的复制构造函数?
- 如何在将原始指针移动到基类构造函数之前从unique_ptr中提取原始指针
- 为包含原始指针的对象C++智能指针
- c++:复制、删除和运算符=在原始指针映射中
- C++模板,用于通过常量引用和原始指针传递向量
- C++为什么原始指针不会增加shared_ptr的引用计数?
- 从shared_ptr获取原始指针以将其传递给需要 raw 的函数
- 如何包装多级原始指针以赋予其容器语义
- 为什么我可以通过原始指针而不是shared_ptr来修改对象
- 将原始指针传递给接受unique_ptr作为参数的函数
- 为什么我们不允许将纯引用参数传递给 std::thread,但允许传递原始指针?
- 更改保留指向其字段的原始指针的对象地址
- 从原始指针(衰减的 C 样式数组)和大小生成范围::视图
- 如何在C++代码中灵活使用和替换标准::shared_ptr或标准::unique_ptr或原始指针?