Google

SWIG/Examples/perl5/funcptr/

Pointers to Functions

$Header: /cvs/projects/SWIG/Examples/perl5/funcptr/index.html,v 1.1 2000/09/04 15:43:52 beazley Exp $

Okay, just what in the heck does SWIG do with a declaration like this?

int do_op(int a, int b, int (*op)(int, int));
Well, it creates a wrapper as usual. Of course, that does raise some questions about the third argument (the pointer to a function).

In this case, SWIG will wrap the function pointer as it does for all other pointers. However, in order to actually call this function from a script, you will need to pass some kind of C function pointer object. In C, this is easy, you just supply a function name as an argument like this:

/* Some callback function */
int add(int a, int b) {
   return a+b;
} 
...
int r = do_op(x,y,add);
To make this work with SWIG, you will need to do a little extra work. Specifically, you need to create some function pointer objects using the %constant directive like this:
%constant(int (*)(int,int)) ADD = add;
Now, in a script, you would do this:
$r = do_op($x,$y, $ADD);

An Example

Here are some files that illustrate this with a simple example:

Notes

  • The value of a function pointer must correspond to a function written in C or C++. It is not possible to pass an arbitrary Perl function object in as a substitute for a C function pointer.

  • A perl function can be used as a C/C++ callback if you write some clever typemaps and are very careful about how you create your extension. This is an advanced topic not covered here.