Calculate array index from pointers
Me and some peers are working on a game (Rigs ofRods) and trying to integrate OpenCL for physics computation. At the same time, we are trying to do the much needed cleanup of our data structures. I guess I should say that we are trying to clean up our data structures and be mindful of the OpenCL requirements.
One of the problems with using open CL is the inability to use pointers because the memory space is different. From what little is known about OpenCL, all data is copied to the GPU, then it does the computation, the pointer values ββwill be copied, but the address will not match the expected address.
The data in question is centralized in the array, when objects need this data, they use pointers on the desired object, or store the array index.
One solution for OpenCL accounting is to use array index instead of pointers. This leads to a tight bond that can lead to headaches later on. As a solution, I got the idea of ββcalculating the array index based on the start address and the current address. This will of course only work with a contiguous array.
I wrote a sample app to test this and it worked just fine, some people have tested it on different platforms as well.
#include <iostream>
typedef struct beam_t
{
unsigned int item;
} beam_t;
#define GLOBAL_STATIC_ASSERT(expr, msg) \
extern char STATIC_ASSERTION__##msg[1]; \
extern char STATIC_ASSERTION__##msg[(expr)?1:2]
#ifdef __amd64
typedef unsigned long pointer_int;
#else
typedef unsigned int pointer_int;
#endif
GLOBAL_STATIC_ASSERT(sizeof(pointer_int) == sizeof(pointer_int*), integer_size);
#define MAX_BEAM 5
int main ()
{
beam_t beams[MAX_BEAM];
beam_t* beam_start = &beams[0];
beam_t* beam_ptr = NULL;
std::cout << "beams: " << &beams << "\n";
for( pointer_int i = 0; i < MAX_BEAM; ++i )
{
beam_ptr = &beams[i];
pointer_int diff = ((pointer_int)beam_ptr - (pointer_int)beam_start);
std::cout << "beams[" << i << "]: " << beam_ptr
<< "\t calculated index:" << diff / sizeof(beam_t)
<< "\n";
}
return 0;
}
I'm concerned that this is more than an ingrained solution. I know this won't work without unsafe memory.
Basically, my questions are:
What would be the problems using this approach in known everyday memory?
How could you say it was continuous?
What approaches are used by people to solve this problem?
Thanks and my sentences, if formatting is off this is my first question asking a question.
source to share