PageRenderTime 17ms CodeModel.GetById 14ms app.highlight 1ms RepoModel.GetById 1ms app.codeStats 0ms

/trunk/Examples/java/funcptr/index.html

#
HTML | 91 lines | 67 code | 24 blank | 0 comment | 0 complexity | 9557ec89f9af17d181725375106dc419 MD5 | raw file
 1<html>
 2<head>
 3<title>SWIG:Examples:java:funcptr</title>
 4</head>
 5
 6<body bgcolor="#ffffff">
 7
 8
 9<tt>SWIG/Examples/java/funcptr/</tt>
10<hr>
11
12<H2>Pointers to Functions</H2>
13
14<p>
15Okay, just what in the heck does SWIG do with a declaration like this?
16
17<blockquote>
18<pre>
19int do_op(int a, int b, int (*op)(int, int));
20</pre>
21</blockquote>
22
23Well, it creates a wrapper as usual.  Of course, that does raise some
24questions about the third argument (the pointer to a function). 
25
26<p>
27In this case, SWIG will wrap the function pointer as it does for all other
28pointers.  However, in order to actually call this function from a Java program,
29you will need to pass some kind of C function pointer object.  In C,
30this is easy, you just supply a function name as an argument like this:
31
32<blockquote>
33<pre>
34/* Some callback function */
35int add(int a, int b) {
36   return a+b;
37} 
38...
39int r = do_op(x,y,add);
40</pre>
41</blockquote>
42
43To make this work with SWIG, you will need to do a little extra work.  Specifically,
44you 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
52Now, in a Java program, you would do this:
53
54<blockquote>
55<pre>
56int r = do_op(x,y, example.ADD)
57</pre>
58</blockquote>
59where <tt>example</tt> is the module name.
60
61<h2>An Example</h2>
62
63Here are some files that illustrate this with a simple example:
64
65<ul>
66<li><a href="example.c">example.c</a>
67<li><a href="example.h">example.h</a>
68<li><a href="example.i">example.i</a> (SWIG interface)
69<li><a href="runme.java">runme.java</a> (Sample program)
70</ul>
71
72<h2>Notes</h2>
73
74<ul>
75<li>The value of a function pointer must correspond to a function written in C or C++.
76It is not possible to pass an arbitrary Java function in as a substitute for a C 
77function pointer.
78
79<p>
80<li>A Java function can be used as a C/C++ callback if you write some
81clever typemaps and are very careful about how you create your extension.
82This is an advanced topic not covered here.
83</ul>
84
85<hr>
86</body>
87</html>
88
89
90
91