我有一个 CUDA 应用程序,我正在处理一组对象;每个对象都有一个指向 std::pair<int, double>
数组的指针.我正在尝试 cudaMemcpy 对象数组,然后 cudaMemcpy 对每个对象的数组,但这给我带来了各种各样的悲伤。尝试复制到内部数组时崩溃;我不明白如何将其移动...
#include <cuda.h>
#include <cuda_runtime.h>
#include <iostream>
using namespace std;
class Object
{
public:
int id;
float something;
std::pair<int, float> *somePairs;
};
Object *objects;
void initObjects()
{
objects = new Object[10];
for( int idx = 0; idx < 10; idx++ )
{
objects[idx].id = idx;
objects[idx].something = (float) idx;
objects[idx].somePairs = new std::pair<int, float>[10];
for ( int jdx = 10; jdx < 10; jdx++ )
{
objects[idx].somePairs[jdx] = std::pair<int, float>( jdx, (float) jdx );
}
}
}
void cudaMemcpyObjects()
{
Object *devObjects;
cudaMalloc( &devObjects, sizeof(Object) * 10 );
cudaMemcpy( devObjects, objects, sizeof(Object) * 10, cudaMemcpyHostToDevice );
for ( int idx = 0; idx < 10; idx++ )
{
size_t pairSetSize = sizeof(std::pair<int, float>) * 10;
// CRASH HERE ... v
cudaMalloc( &(devObjects[idx].somePairs), pairSetSize );
cudaMemcpy( devObjects[idx].somePairs, objects[idx].somePairs,
sizeof( std::pair<int, float> ) * 10, cudaMemcpyHostToDevice );
}
}
int main()
{
initObjects();
cudaMemcpyObjects();
return 0;
}
最佳答案
我的 CUDA 经验才刚刚起步,但我相信错误是这样的:
cudaMalloc
是一个host 函数,它希望将指针写入host 内存。但是,您正在向它传递一个设备 内存中的指针!
要解决这个问题,您应该首先创 build 备指针并将它们填充到您的主机对象结构中,然后才将整个指针复制到设备上,并将各个对也复制到设备上。
示意图:
struct Bar;
struct Foo
{
int tag;
Bar * bp;
};
void setup()
{
Foo * hFoo = new Foo[10];
Foo * dFoo;
cudaMalloc(dFoo, sizeof(Foo) * 10);
for (size_t i = 0; i != 10; ++i)
{
Bar * dBar;
cudaMalloc(&dbar, sizeof(Bar));
Bar b; // automatic temporary -- we never keep a host copy of this
cudaMemcpy(dBar, &b, sizeof(Bar));
hFoo[i].bp = dBar; // this is already a device pointer!
}
cudaMemcpy(dFoo, hFoo, sizeof(Foo) * 10);
}
在返回时,不要忘记Foo::bp
是设备 指针,您仍然需要一个一个地复制回去!
只拥有一个可以一次性移动的独立类可能会更容易,但这可能不切实际,或者由于内存局部性的原因而不可取。你必须仔细考虑这一点。如果成员只是一对,为什么不把这两个项目直接放在主类中呢?
关于c++ - CUDA - 复制到对象数组中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6929626/