Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenGL with C++: vtable troubles when passing class array to glTexImage2d

I made a class Color with float r, float g, float b, float alpha. It has a base class with a virtual destructor.

I am trying to pass an array of Color to the opengl function glTexImage2D, with a GL_RGBA organization of type float (which would be an array of {float r, float g, float b, float alpha}). This requires Color to contain only 4 floats (size of 16 bytes).

However, sizeof(Color) reveals that my class has a size of 20 bytes due to the base class of Color having a vtable, thanks to the destructor.

How can I keep my vtable and still pass my Color array to glTexImage2D?

like image 264
Nicolas Lutz Avatar asked Feb 08 '23 02:02

Nicolas Lutz


1 Answers

Short answer: No, you can't do that.

You can see all the extra parameters for glTexImage2D() in the glPixelStore() documentation. As you can see, there are no parameters for adding a "stride" or "padding" between pixels. There are options for adding space at the beginning or end of rows, or between images (3D), but nothing between pixels.

Advice: An array of identical 4D vectors with a vtable for each is a design smell. It is a bad design. Your color type, in order to be compatible with C, should be a standard layout type. Note that in particular this means that you cannot use virtual functions.

If you really need a base type with a virtual destructor, create a wrapper type.

like image 196
Dietrich Epp Avatar answered Feb 10 '23 17:02

Dietrich Epp