See what's going on with flipcode!




This section of the archives stores flipcode's complete Developer Toolbox collection, featuring a variety of mini-articles and source code contributions from our readers.

 

  Function Pointers To Member Functions
  Submitted by



I was faced with a problem with function pointers not so long ago. Specifically having a function ptr to a non static class member function ...

Having a member variable pointing to a member function is no problem as is having a variable pointing to a static member function.

But there is no documented way to store a pointer to a non-static member function outside of the class.

Yes, I know, you could still pass a pointer to the class to your function so it will be able to call non-static functions but it just doesn't seems right/efficient...

Well, here's what I came up with:

//***************************
// Save the pointer
//***************************

// in_pFunction is of type : void (CClassName::*in_pFunction)() in this example
// The compiler won't let you store the address of a non static function if you
// don't store it in a member variable of the class. But, it will let you use the
// address of the pointer ;-)

// Store the function pointer in a variable
void *pData = *( (void **) &in_pFunction );

// you can now store pData wherever you want since it's a void ptr //*************************** // Use the pointer //*************************** // Now that our pointer is safely stored, we have to get it back. // We can't cast a pointer to a non static member function pointer so we use the // address of the pointer and change the value it's pointing to :-) // Declare a variable to store the function pointer. void (CClassName::*pClassFunction)() = NULL;

// Because we can't cast our void pointer to a member function pointer, store the // address of the function pointer void **ppvFunction = ( ( void ** ) &pClassFunction );

// pData contains the pointer stored earlier... // Since *ppvFunction is the same as pClassFunction we can assign it the value // that was stored in our void pointer pData *ppvFunction = pData;

// Call the function a pointer to the class // If we were to use the pointer directly, the function will be called by creating // a temporary instance of the call (this-*pClassFunction)();



The zip file viewer built into the Developer Toolbox made use of the zlib library, as well as the zlibdll source additions.

 

Copyright 1999-2008 (C) FLIPCODE.COM and/or the original content author(s). All rights reserved.
Please read our Terms, Conditions, and Privacy information.