Home arrow C++ arrow Page 3 - Function Pointers, part 3

Function Pointers, part 3

In previous articles, Jun Nakamura introduced using regular function pointers, C++ class member function pointers, and declaring pointers to the members of classes. In this article, he writes about calling conventions, callback functions, and begins to talk about using functors.

Author Info:
By: J. Nakamura
Rating: 5 stars5 stars5 stars5 stars5 stars / 15
June 07, 2005
  1. · Function Pointers, part 3
  2. · Windows Calling Conventions
  3. · Application of Callback Functions
  4. · Functors Encapsulate Function Pointers

print this article

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
  // 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]);

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.

blog comments powered by Disqus

- Intel Threading Building Blocks
- Threading Building Blocks with C++
- Video Memory Programming in Text Mode
- 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++

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 

Developer Shed Affiliates


© 2003-2019 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials