PDA

View Full Version : Callback functions in openGL



Madonna
05-10-2009, 10:33 AM
Hi
I have the following problem.. I did a class called Keyboard
having functions inputKey and myKeyboard.
I made an object of that class (Keyboard k) in the main
when I tried to do the following:
glutSpecialFunc(k.inputKey);
glutKeyboardFunc(k.myKeyboard);

I get an error : left of '.inputKey' must have class/struct/union
when I tried
glutSpecialFunc(&Keyboard::inputKey);
glutKeyboardFunc(&Keyboard::myKeyboard);

I get another error: 'glutSpecialFunc' : cannot convert parameter 1 from 'void (__thiscall Keyboard::* )(int,int,int)' to 'void (__cdecl *)(int,int,int)'

does anyone have a solution for this?
I need to call the functions I did in the class keyboard into glutSpecialFunc and glutKeyboardFunc

Thank you in advance

dletozeun
05-10-2009, 02:00 PM
Try this in the Keyboard class declaration:




class Keyboard
{
void __cdecl inputKey( int, int, int );
...
};

Madonna
05-10-2009, 02:12 PM
No it didn't work :S

for elaborating more
here is part of the code

//main.h
class Keyboard
{ public:
Keyboard();
~Keyboard();
void inputKey(int key,int x,int y);
void myKeyboard(unsigned char key, int x,int y);
};
[\code]
and this is the Keyboard class
[CODE]
#include "main.h"

Keyboard::Keyboard(){}
Camera c(x,y,z,lx,ly,lz,angle);

void Keyboard::inputKey(int key, int x, int y) {

switch (key) {
case GLUT_KEY_LEFT :
angle -= 0.01f;
c.orientMe(angle);break;
case GLUT_KEY_RIGHT :
angle +=0.01f;
c.orientMe(angle);break;
case GLUT_KEY_UP :
c.moveMeFlat(1);break;
case GLUT_KEY_DOWN :
c.moveMeFlat(-1);break;

case GLUT_KEY_PAGE_UP:
c.moveme(1);break;
case GLUT_KEY_PAGE_DOWN:
c.moveme(-1);break;

}
}
void Keyboard::myKeyboard(unsigned char key,int x, int y){

switch(key){

case 'q':
drawSphere=false;break;
case 's':
drawSphere=true;break;

}

}
[\code]
for the main.cpp
[CODE]
#include "main.h"
//some code here
Keyboard k;
void main(int argc, char **argv)
{
//---------
glutSpecialFunc(k.inputKey);
glutKeyboardFunc(k.myKeyboard);
// ------

}
[\code]

dletozeun
05-10-2009, 02:39 PM
Make your Keyboard callback methods static or if it is not possible write a static wrapping method in the class Keyboard that calls the proper keyboard callback of a Keyboard object.

BTW, the end code tag is [/CODE] and not [\code]. :)

Rosario Leonardi
05-11-2009, 02:58 AM
class method use the _thiscall, the first parameter will always be the "this" pointer.
With static as dletozeun suggest you have a standard call but then the Keyboard class will be useless cause you can modify only static attributes.

You can do something like that:


Keyboard *k;

void dummyKeyFunc(int k, int x, int y)
{
k->keyInput(k, x, y);
}

void main(int argc, char **argv)
{
k = Keyboard::getInstance(); //use singleton for manager
glutSpecialFunc(dummyKeyFunc);
glutKeyboardFunc(dummyKeyFunc);
}

By the way using a class method to modify a global variable is a very bad design issue. Check again your class relationship.