store in class a pointer to ordinary function and call it
hi there,
im trying to save in a private member of my class, a pointer to a ordinary or global function (not a member/method one), so i can call is when certain events happen.
for example:
class Test
{
private:
int number;
void * ptr_to_func; //can i use void? this is the pointer to a global function
public:
Test()
{
this->number = 0;
this->ptr_to_func = 0;
}
void set_callback( void (*callback)() ) //this is where i set the global func
{
this->ptr_to_func = &callback //store the adress
}
void add( int number ) //just a test method
{
this->number += number;
if( this->number == 10 && this->ptr_to_func ) //is number == 10 and is the ptr_to_func valid?
{
this->callback(); //this should call the global function, instead it gives me a error C2064: term does not evaluate to a function taking 0 arguments
}
}
};
void print() //our global function
{
std::cout << "the number is now 10!" << std::endl;
}
int main( int argc, char *argv[] ) //main function and setup
{
Test t;
t.set_callback( print); //sets print as a callback function
for( int i = 0; i < 10; i++ )
t.add( 1 ); //yes 1, not i, so the t.number gets to 10
return 0;
}
the function name is the address. So you just store
this->ptr_to_func = callback
The other way you had it was a void **
Here is a quick sample application on how to accomplish what you want..
output:
I'm a useless function!
hth
moe.ron
this->ptr_to_func = callback
The other way you had it was a void **
Here is a quick sample application on how to accomplish what you want..
#include <iostream>// simple typedef for my function ptrtypedef void (*pfn)(void);void blah(){ std::cout << "I'm a useless function!" << std::endl;}struct foo{ foo():pFunc(0){} virtual ~foo(){} pfn pFunc; void Set( pfn func ) { pFunc = func; } void Use(void) { if(pFunc) (*pFunc)(); }};int main(){ foo bar; bar.Set(blah); bar.Use(); return(0);}
output:
I'm a useless function!
hth
moe.ron
it works now, guess i cant have a "void * func" as a pointer to a function but only a "void (*func)()"
thanks a lot :)
Quote:Original post by a2ps
it works now, guess i cant have a "void * func" as a pointer to a function but only a "void (*func)()"
thanks a lot :)
You guessed right. void * func is a pointer to a non-typed memory zone. It is not a pointer to a function at all.
Regards,
Quote:Original post by a2ps
it works now, guess i cant have a "void * func" as a pointer to a function but only a "void (*func)()"
thanks a lot :)
I would really suggest just using a typedef like I did. It makes it easier to read and its a lot less typing...
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement