summaryrefslogtreecommitdiff
path: root/Examples/java/funcptr/index.html
blob: 0ad2be1cfa11f9974022f7a705d238e40ea3b60d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<html>
<head>
<title>SWIG:Examples:java:funcptr</title>
</head>

<body bgcolor="#ffffff">


<tt>SWIG/Examples/java/funcptr/</tt>
<hr>

<H2>Pointers to Functions</H2>

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

<blockquote>
<pre>
int do_op(int a, int b, int (*op)(int, int));
</pre>
</blockquote>

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

<p>
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 Java program,
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:

<blockquote>
<pre>
/* Some callback function */
int add(int a, int b) {
   return a+b;
} 
...
int r = do_op(x,y,add);
</pre>
</blockquote>

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:

<blockquote>
<pre>
%constant(int (*)(int,int)) ADD = add;
</pre>
</blockquote>

Now, in a Java program, you would do this:

<blockquote>
<pre>
int r = do_op(x,y, example.ADD)
</pre>
</blockquote>
where <tt>example</tt> is the module name.

<h2>An Example</h2>

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

<ul>
<li><a href="example.c">example.c</a>
<li><a href="example.h">example.h</a>
<li><a href="example.i">example.i</a> (SWIG interface)
<li><a href="main.java">main.java</a> (Sample program)
</ul>

<h2>Notes</h2>

<ul>
<li>The value of a function pointer must correspond to a function written in C or C++.
It is not possible to pass an arbitrary Java function in as a substitute for a C 
function pointer.

<p>
<li>A Java 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.
</ul>

<hr>
</body>
</html>