3 <title>SWIG:Examples:perl5:funcptr</title>
6 <body bgcolor="#ffffff">
9 <tt>SWIG/Examples/perl5/funcptr/</tt>
12 <H2>Pointers to Functions</H2>
15 Okay, just what in the heck does SWIG do with a declaration like this?
19 int do_op(int a, int b, int (*op)(int, int));
23 Well, it creates a wrapper as usual. Of course, that does raise some
24 questions about the third argument (the pointer to a function).
27 In this case, SWIG will wrap the function pointer as it does for all other
28 pointers. However, in order to actually call this function from a script,
29 you will need to pass some kind of C function pointer object. In C,
30 this is easy, you just supply a function name as an argument like this:
34 /* Some callback function */
35 int add(int a, int b) {
39 int r = do_op(x,y,add);
43 To make this work with SWIG, you will need to do a little extra work. Specifically,
44 you need to create some function pointer objects using the %constant directive like this:
48 %constant(int (*)(int,int)) ADD = add;
52 Now, in a script, you would do this:
56 $r = do_op($x,$y, $ADD);
62 Here are some files that illustrate this with a simple example:
65 <li><a href="example.c">example.c</a>
66 <li><a href="example.h">example.h</a>
67 <li><a href="example.i">example.i</a> (SWIG interface)
68 <li><a href="runme.pl">runme.pl</a> (Sample script)
74 <li>The value of a function pointer must correspond to a function written in C or C++.
75 It is not possible to pass an arbitrary Perl function object in as a substitute for a C
79 <li>A perl function can be used as a C/C++ callback if you write some
80 clever typemaps and are very careful about how you create your extension.
81 This is an advanced topic not covered here.