Thread: Callback functions

  1. #1
    Registered User
    Join Date
    Apr 2002
    Posts
    110

    Callback functions

    Okay, probably more of a generic c topic but am writing the program in c++.

    What I am wanting to know is how would I go about writing a callback function.

    The term 'callback function' I am using to describe the process through which function A has the name of function B passed to it and will then call function B.

    As I am going to be passing it the name of a function that resides within a c++ class, are there any particular circumstances that need to be adhered to?
    WebmasterMattD
    WebmasterMattD.NET

  2. #2
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,981
    Code:
    #include <iostream>
    using namespace std;
    
    int foo(long l)
    {
        cout << "foo(" << l << ")" << endl;
        return 0;
    }//foo
    
    int bar(long l)
    {
        cout << "bar(" << l << ")" << endl;
        return 1;
    }//bar
    
    // create a typename for a pointer to a function 
    // that returns int takes one long parameter
    typedef int (*foobar_ptr_t)(long);
    
    int main()
    {
        foobar_ptr_t fp1, fp2;
    
        fp1 = foo;
    
        // address-of operator (&) is ok too
        fp2 = &bar;
    
        fp1(1);
        fp2(2);
    
        return 0;
    }//main
    gg

  3. #3
    mustang benny bennyandthejets's Avatar
    Join Date
    Jul 2002
    Posts
    1,401
    You may have to make the member function static. I believe it is not possible to pass a non-static member function pointer to a callback function. On the topic of function pointers, here is a good site.

    You probably don't want to pass a string for the function, to be used with GetProcAddress32(). Function pointers are much better suited for this purpose.

    What does the program actually do?
    [email protected]
    Microsoft Visual Studio .NET 2003 Enterprise Architect
    Windows XP Pro

    Code Tags
    Programming FAQ
    Tutorials

  4. #4
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,981
    You can apply the above code using class methods as long as they are declared static.
    If you want the use "pointer to non-static member function" semantics, then read this.

    gg

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. An array of macro functions?
    By someprogr in forum C Programming
    Replies: 6
    Last Post: 01-28-2009, 07:05 PM
  2. Replies: 7
    Last Post: 11-17-2008, 01:00 PM
  3. Replies: 1
    Last Post: 08-24-2008, 11:39 AM
  4. Callback Functions
    By valaris in forum C Programming
    Replies: 11
    Last Post: 07-31-2008, 09:20 PM
  5. Passing pointers between functions
    By heygirls_uk in forum C Programming
    Replies: 5
    Last Post: 01-09-2004, 06:58 PM