Indexing in jCuda Pointer function

228 views Asked by At

How does one index in, lets say a 1D "Result" array, using the function pointer.to(int[ ]) in jCuda. I want to write a chunk of data into the first n locations of "Result" and the next chunk of data into Result[0 + chunk] onwards, and so on.

Unlike C, i cannot say Result+chunk and get on with life. how do i index to an intermediate location then?

1

There are 1 answers

0
Marco13 On

Assuming that you are refering to JCuda from jcuda.org:

When you created a Pointer to an int array using Pointer#to(int[]), you can create a Pointer with a certain byte offset using the Pointer#withByteOffset(long) method. So in this example:

Pointer p = Pointer.to(intArray);
Pointer next = p.withByteOffset(chunkSize * Sizeof.INT);

This method creates only a "view" on the particular position in the array. It does not copy any data or so. The resulting pointer will just point to the 'chunkSize'th element of the array. Thus, it is the "Java version" of the C construct

int *p = ...
int *next = p + chunkSize;

that you mentioned.

Important: Make sure to really multiply the intended offset by the size of the elements in the array! It has to be a BYTE offset, so the 'chunkSize' has to be multiplied with Sizeof.INT to really point to the right position in the int[] array. (In C, this multiplication is done implicitly, based on the pointer type. But since the Pointer in Java has no associated type, you always have to specify the BYTE offset)

Hint: When you frequently need such offset-pointers of a particular type, the readability can be increased with a helper method like this

private static Pointer at(Pointer p, int offsetInInts)
{
    int offsetInBytes = offsetInInts * Sizeof.INT;
    return p.withByteOffset(offsetInBytes);
}

that you can use inside a method call:

// C version:
cudaMemcpy(p + chunkSize * i, ...);

// Java version:
cudaMemcpy(at(p, chunkSize * i), ...);