import source from 1.3.40
[external/swig.git] / Examples / perl5 / funcptr / index.html
1 <html>
2 <head>
3 <title>SWIG:Examples:perl5:funcptr</title>
4 </head>
5
6 <body bgcolor="#ffffff">
7
8
9 <tt>SWIG/Examples/perl5/funcptr/</tt>
10 <hr>
11
12 <H2>Pointers to Functions</H2>
13
14 <p>
15 Okay, just what in the heck does SWIG do with a declaration like this?
16
17 <blockquote>
18 <pre>
19 int do_op(int a, int b, int (*op)(int, int));
20 </pre>
21 </blockquote>
22
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). 
25
26 <p>
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:
31
32 <blockquote>
33 <pre>
34 /* Some callback function */
35 int add(int a, int b) {
36    return a+b;
37
38 ...
39 int r = do_op(x,y,add);
40 </pre>
41 </blockquote>
42
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:
45
46 <blockquote>
47 <pre>
48 %constant(int (*)(int,int)) ADD = add;
49 </pre>
50 </blockquote>
51
52 Now, in a script, you would do this:
53
54 <blockquote>
55 <pre>
56 $r = do_op($x,$y, $ADD);
57 </pre>
58 </blockquote>
59
60 <h2>An Example</h2>
61
62 Here are some files that illustrate this with a simple example:
63
64 <ul>
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)
69 </ul>
70
71 <h2>Notes</h2>
72
73 <ul>
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 
76 function pointer.
77
78 <p>
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.
82 </ul>
83
84 <hr>
85 </body>
86 </html>
87
88
89
90