To pass a pointer to a member function

I have a class with instance functions (or methods?). From the instance I am trying to pass pointers to these functions to the library. The library expects static functions.

When I pass my pointers to callback functions, the compiler complains that my functions are not static. I tried to make them static, but if I do, then I can’t access the instance fields inside the functions.

How can I get around this?

A similar question: Using a member function of a C ++ class as a C callback function , where they suggest setting a method. However, I cannot do this, or I do not understand how I could.

The code

GlutController::GlutController (int argc, char **argv) {

   // stuff ..

   // Register callbacks
   glutSpecialFunc( OnSpecialKeys );  // Error, need static functions
   glutReshapeFunc( OnChangeSize );   // Error...
   glutDisplayFunc( OnRenderScene );  // Error...

   // stuff ..
}

GlutController::~GlutController() {

}

void GlutController::OnChangeSize(int aNewWidth, int aNewHeight){

   glViewport(0,0,aNewWidth, aNewHeight);
   mViewFrustrum.SetPerspective( APP_CAMERA_FOV,             // If this function is 
            float( aNewWidth ) / float( aNewHeight ),        // static, this won't 
            APP_CAMERA_NEAR,                                 // work
            APP_CAMERA_FAR );
   mProjectionMatrixStack.LoadMatrix(                        // Same here
            mViewFrustrum.GetProjectionMatrix() );
   mTransformPipeline.SetMatrixStacks(mModelViewMatrixStack, // Same here  
            mProjectionMatrixStack);

}

void GlutController::OnRenderScene(void){
   mGeometryContainer.draw();                                // Won't work if static
}

void GlutController::OnSpecialKeys(int key, int x, int y){
   mGeometryContainer.updateKeys(key);                       // Won't work if static
}

: ++. ++, , . Java.

+5
4

, , . glut.

:

  • glut , ,
  • , ,

. , glut , .

, . SDL.

+7

, . - ++ "" . , .

, , , , , . . GlutController ( , ), .

+3

, -, , GlutInstance ( + , ).

static GlutController* s_this;

static void s_OnChangeSize(int w, int h) { s_this->OnChangeSize(w, h); }

GlutController::GlutController (int argc, char **argv) { 
   s_this = this;

   glutSpecialFunc(s_OnSpecialKeys);
}

GlutController::~GlutController() { s_this= 0; } 

void GlutController::OnChangeSize(int w, int h) { /* non-static stuff */ }

s_thisdisplayed only in the local file, for example. not visible to any code that calls the GlutController constructor from another file.

+2
source

you must have static methodand instance(possibly static) to call a member function instanceof the function fromstatic

Something like that:

//static method
void MyClass::myCallback()
{
    static MyClass instance; //or you can store your in instance in some Singleton, or
    //possibly create a temporary
    instance.nonStaticMethod();
}
+1
source

All Articles