I have a problem for which I hope one of you c experts have a solution. I must
write an openGL application and am required to use C or C++ and glut. I come
from an object-oriented mindset, therefore I gravitate toward C++. Now glut
requires C-functions to be passed for the callbacks, but there is a mismatch
between the type of a "c function" and a "c++ member function". I was told,
"Just hack something together with C." Well, that goes against my grain. I
want all the benefits that come with OO, especially reuse. (Besides, I have to
be able to read my own code, and from what I see in the example c code I've
been given, that is hard to achieve in C.)
Caveat: I am new to C so my knowledge of the syntax, especially with pointers
and pointers to functions, is lacking, so I will try to use pseudo-code in
hopes that someone can clean it up if what I want to do is possible.
With that out of my system let me use one of the glut features as an example.
glutReshapeFunc (onReshape) tells glut to call onReshape when the window size
changes. onReshape must have two int arguments:
onReshape (int aHeight, int aWidth)
Ideally, I would like to do this in main():
displayable myWin;
// where displayable is a C++ object whose class
// has method `onReshape' taking two int arguments.
glutReshapeFunc (myWin::onReshape);
better yet, in the constructor for displayable:
displayable() {
glutCreateWindow(); // etc.
glutReshapeFunc (onReshape);
};
but this will not work because of the type mismatch as mentioned above. So I
do this:
displayable* myWin := NULL
void myWinReshapeWrapper (int h, int w) {
myWin->onReshape;
};
int main(
) {
// initialize glut
glutCreateWindow("This creates a window");
//
myWin = new displayable;
glutReshapeFunc (myWinReshapeWrapper);
This is a problem because I [and any user of my class] will have to have a
reference to and write a "reshape wrapper" for every single displayable he
wants.
So, given that
1) I can't use C++ member functions in a C callback
2) The "wrapper" method works, but is not scalable
Is there a way to:
Have a method (c++ member, or a c-function included at the top of the
class "displayable"), called in the constructor that can do this wrapping
automatically. Something like:
function* makeWrapper (displayable* dis, function* func)
// given reference to a displayable and some function
// return a new function that simulates "dis->func"
And then in the constructor:
displayable() {
glutCreateWindow();
f = makeWrapper (this, onReshape)
glutDisplayFunc (f);
To boil it down, I want to create new functions to be used as callbacks which
will call a c++ method on the correct object.
To anyone who has read this far, I thank you.
Best regards,
Jimmy J. Johnson