I'm doing a little graphics programming and I have a two dimentional array (that varies in size during program execution) that I store using openGL.
So when I go to access it, all I get is a void
pointer back.
To make the logic easier, I want the compiler to pretend that it is, and use it as, a 2D array (because arr[i][j]
is more concise and less error prone than ptr[i * y + j]
).
This clever method of casting I found works fine in GCC (on the linux machines at uni):
Vertex (&vertices)[tess][tess] = *reinterpret_cast<Vertex (*)[tess][tess]>(
glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY)
);
Which basically casts the block of memory pointer openGL gave me to a tess X tess
2D array, and creates a reference of that type to point at it.
This allows me to access the memory like vertices[i][j]
.
Vertex
is just a typedef
ed struct
containing float
s
However, at home on my Windows machine, VS'12 has a hissy fit, complaining that it requires the integers where tess
is written to be constant
(specifically; error C2057: expected constant expression
).
I have no idea why.
Now, I understand that VS doesn't support VLA's, but I am not creating an array here, I'm creating a reference to something that I don't know the size of 'till runtime.
So it shouldn't care if the size changes between function calls, right? Why is this not allowed?
Not to be deterred I tried using std::array
std::array<std::array<Vertex, tess>, tess>& vertices;
And apart from the obvious references must be initialized
this test didn't help me because it still complained about expression must have a constant value
(specifically; error C2975: '_Size' : invalid template argument for 'std::array', expected compile-time constant expression
)
I am at a loss at what to try here, I was so proud of the reinterpret_cast
and how simple it made things and was sure I wasn't using a method that was contravening the standard.
I don't want to create a std::vector
from the pointer then copy the data from that dynamic array back into the pointer location when I'm finished; that just seems so inefficient when the memory block is already just sitting there!
There's no way to create a vector around a pre-existing block of memory, is there? ..no that sounds silly.
I want to see if this can be done without giving up and just using it as Vertex*
; Ideas?
Can someone enlighten me as to why it isn't working in VS?
Is there something I can do to get it working (extensions/updates to VS)?
Does VS'13 add support for this?
I am also getting the error C2087: 'vertices' : missing subscript
that I can't explain.
As well as these other errors that seem to show VS desperately wants tess
to be constant:
error C2466: cannot allocate an array of constant size 0
error C2540: non-constant expression as array bound
error C2440: 'initializing' : cannot convert from 'Vertex [1][1]' to 'Vertex (&)[][1]'