Reputation: 568
Say, I have a structure like
struct vertex
{
int x;
int y;
int z;
}
and I make a pointer array like
vertex *points = new vertex[100];
so, at a point I require just the x members of that pointer array. So how can i do that?
eg a new pointer : int *xPoints=new int[100];
and in this i want to store all the x members of the vertex. Is there any command to do that? i dont want to do that using loop, i want to do that using special memcopy or something.
Upvotes: 0
Views: 106
Reputation: 151879
cudaMemcpy2D can be used to copy between host and device when either the source or destination (or both) data should be strided.
Here's a worked example:
$ cat t553.cu
#include <stdio.h>
#define DSIZE 4
struct vertex {
int x,y,z;
};
__global__ void mykernel(int *data, unsigned length){
for (int i = 0; i < length; i ++) printf("kernel data[%d] = %d\n",i,data[i]);
}
int main(){
vertex *points = new vertex[DSIZE];
for (int i = 0; i < DSIZE; i++){
points[i].x = 1;
points[i].y = 2;
points[i].z = 3;}
int *d_ypoints;
cudaMalloc(&d_ypoints, DSIZE*sizeof(int));
cudaMemcpy2D(d_ypoints, sizeof(int), ((int *)points)+1, 3*sizeof(int), sizeof(int), DSIZE, cudaMemcpyHostToDevice);
mykernel<<<1,1>>>(d_ypoints, DSIZE);
cudaDeviceSynchronize();
return 0;
}
$ nvcc -arch=sm_20 -o t553 t553.cu
$ cuda-memcheck ./t553
========= CUDA-MEMCHECK
kernel data[0] = 2
kernel data[1] = 2
kernel data[2] = 2
kernel data[3] = 2
========= ERROR SUMMARY: 0 errors
$
Parsing out the cudaMemcpy2D
operation:
cudaMemcpy2D(d_ypoints, // starting pointer on the device (destination)
sizeof(int), // stride on device (i.e. no stride)
((int *)points)+1, // starting pointer on host (.y element of first struct)
3*sizeof(int), // stride on host (distance between consecutive .y elements)
sizeof(int), // number of bytes to transfer per "row"
DSIZE, // number of "rows" to transfer
cudaMemcpyHostToDevice); // direction of transfer
Upvotes: 1