Advertisement

tips on passing function pointers (classes)

Started by July 10, 2001 05:34 PM
0 comments, last by jho 23 years, 7 months ago
I have a question, I have a function where it is expected to take a pointer to a function of the a certain protoype. lets say, typedef BOOL myfuntype(int n); <- a prototype Now I have a class with this function BOOL myClass::myfun(int n) <-matches the prototype { //access some myClass private members } How can I pass "myfun" as a parameter (as a function pointer?) I can''t seem to compile unless myfun is a static member function, but then static member function seemed worthless to me because I can''t access specific member VARIABLEs of the class I am using.
Member functions of a class use the "thiscall" calling convention. "thiscall" is different to the normal __cdecl which static members and methods with variable arguments use. Some of which are:

- name mangling. The number and type of arguments are mangled into the name of the method
- callee stack cleanup. The callee must cleanup the stack - normally the caller cleans up the stack, which allows for variable arguments, but produces slightly larger code.
- "thiscall" is not a keyword, so you cannot explicitly make a function call "thiscall".

The last point there is why you cannot use thiscall to make function pointers to non-static member functions of a class.

To achieve the same effect, use something like this:

  typedef void (*funcptr)( void *, int );class Foo{public:    static void bar( void *data, int i )    {        Foo *foo = (Foo *)data;        foo->foobar( i );    }    void foobar( int i );}...funcptr ptr = Foo::bar;Foo foo = new Foo;ptr( foo, 100 );  



War Worlds - A 3D Real-Time Strategy game in development.

This topic is closed to new replies.

Advertisement