C++
  Home arrow C++ arrow Page 3 - Function Pointers, part 3
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C++

Function Pointers, part 3
By: J. Nakamura
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 13
    2005-06-07

    Table of Contents:
  • Function Pointers, part 3
  • Windows Calling Conventions
  • Application of Callback Functions
  • Functors Encapsulate Function Pointers

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Function Pointers, part 3 - Application of Callback Functions


    (Page 3 of 4 )

    One of the great concepts of function pointers is that of the callback function. As you have seen it is pretty easy to transform the identity of a function into a pointer, which can point to different implementations of a function with that same identity (they all return the same type and accept the same type of parameters in the same sequence). This means that as long as you create a function that returns the right argument and takes the right argument(s), you can insert your own functionality into other people’s code.

    An excellent example of this is a library that can read and render Macromedia Flash files, but has to run on a lot of different platforms including game consoles. Since memory management is radically different from console to console (there are no malloc or free functions standard on a Nintendo GameCube), the library allows you to register your own memory allocation and deallocation callback functions with it. Whenever it needs a piece of memory, it will use these callbacks, using your memory manager that implements the functionality they need. The library can focus on what it does best: playing .swf files and you can take care of the platform specific details without having to make any changes to the library.

    Let’s look at an example a bit closer to home: qsort. By now you should be able to understand the following function declaration:

    void qsort( void *base
                  , size_t num 
                  , size_t width
                  , int (__cdecl *comp)
                           (const void* e1, const void* e2) 
               );

    You will find it in <stdlib.h> and it is a quicksort implementation that sorts the items in base for you, according to your specification. Now how do you specify it to order your items when it doesn’t know anything about the type of the elements? Simple: provide it with a callback function that tells qsort how to compare two elements with each other.

    The base address of your list of items is given to qsort through the void *base parameter. It can then figure out how to iterate through the items in the list, because you tell it how many items it contains with num and how big each item is with width. Finally the callback function you provide tells qsort whether an item is smaller than, bigger than, or equal to the other item.

    The following example (for Microsoft only, because of the use of _stricmp which is not part of the ANSI standard) reads and sorts the command line parameters using qsort and a callback function.

    #include <stdlib.h>
    #include <string.h>
    #include <stdio.h>

    int comp(void const *arg1, void const *args) {
      // case insensitive comparison
      return _stricmp( *(char**)arg1, *(char**)arg2);
    }

    int main(int argc, char const *argv[])
    {
      // remove application name from argv
      ++argv;
      --argc;
      // sort remaining arguments
      qsort((void*)argv, (size_t)argc, sizeof(char*), comp);
      // display result
      for (int idx=0; idx<argc; ++idx)
        (void)printf(“%s “, argv[idx]);
      (void)printf(“\n”);
    }

    Callback functions can also be very useful when you want to bind a token to a function. One of the examples I have shown you before in the previous article, contains a struct named RQRSTable. It contains a member named function and another one named header. Declared in a .cpp source file, structs like these allow you to configure your token/function binding centrally in the source code. They generally take on the following form:

    static struct <StructName> {
      <member1 type> <member1 name>;
      ... 
      <memberN-1 type> <memberN-1 name>;
      <memberN type> <memberN name>;
    } <array name>[] =
    { { <member value>, ..., <memberN-1 value>, <memberN value> }
    , { <member value>, ..., <memberN-1 value>, <memberN value> }
    ...
    };

    Now that you have a static data object that can describe which function has to execute when a certain token is used. This can be very useful when you are parsing messages, upon which action has to be taken. If you don’t want to iterate to the array sequentially, you can always store the data in a hash table (like std::map) upon initialization and use the token as a key.

    The function pointers in these structs are also callback functions. This is because, just like qsort, the function using them binds data to functions dynamically at runtime. This level of abstraction is very powerful because it allows you to create generic functions like qsort, platform independent libraries etc.

    C++ has more tricks up its sleeve though. Allow me introduce you to functors.

    More C++ Articles
    More By J. Nakamura


     

    C++ ARTICLES

    - More Tricks to Gain Speed in Programming Con...
    - Easy and Efficient Programming for Contests
    - Preparing For Programming Contests
    - Programming Contests: Why Bother?
    - Polymorphism in C++
    - Overview of Virtual Functions
    - Inheritance in C++
    - Extending the Basic Streams in C++
    - Using Stringstreams in C++
    - Custom Stream Manipulation in C++
    - General Stream Manipulation in C++
    - Serialize Your Class into Streams in C++
    - Advanced File Handling with Streams in C++
    - File Handling and Streams in C++
    - The STL String Class







    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 1 Hosted by Hostway
    Stay green...Green IT