Upstream version 1.3.40
[profile/ivi/swig.git] / Examples / java / template / index.html
1 <html>
2 <head>
3 <title>SWIG:Examples:java:template</title>
4 </head>
5
6 <body bgcolor="#ffffff">
7
8
9 <tt>SWIG/Examples/java/template/</tt>
10 <hr>
11
12 <H2>C++ template support</H2>
13
14 <p>
15 This example illustrates how C++ templates can be used from Java using SWIG.
16
17 <h2>The C++ Code</h2>
18
19 Lets take a templated function and a templated class as follows:
20
21 <blockquote>
22 <pre>
23 /* File : example.h */
24
25 // Some template definitions
26
27 template<class T> T max(T a, T b) { return  a&gt;b ? a : b; }
28
29 template<class T> class vector {
30   T *v;
31   int sz;
32  public:
33   vector(int _sz) {
34     v = new T[_sz];
35     sz = _sz;
36   }
37   T &amp;get(int index) {
38     return v[index];
39   }
40   void set(int index, T &amp;val) {
41     v[index] = val;
42   }
43 #ifdef SWIG
44   %addmethods {
45     T getitem(int index) {
46       return self-&gt;get(index);
47     }
48     void setitem(int index, T val) {
49       self-&gt;set(index,val);
50     }
51   }
52 #endif
53 };
54 </pre>
55 </blockquote>
56 The %addmethods is used for a neater interface from Java as the functions <tt>get</tt> and <tt>set</tt> use C++ references to primitive types. These are tricky to use from Java as they end up as a pointer in Java (Java long).
57
58 <h2>The SWIG interface</h2>
59
60 A simple SWIG interface for this can be built by simply grabbing the header file
61 like this:
62
63 <blockquote>
64 <pre>
65 /* File : example.i */
66 %module example
67
68 %{
69 #include "example.h"
70 %}
71
72 /* Let's just grab the original header file here */
73 %include "example.h"
74
75 /* Now instantiate some specific template declarations */
76
77 %template(maxint) max<int>;
78 %template(maxdouble) max<double>;
79 %template(vecint) vector<int>;
80 %template(vecdouble) vector<double>;
81 </pre>
82 </blockquote>
83
84 Note that SWIG parses the templated function <tt>max</tt> and templated class <tt>vector</tt> and so knows about them. However to generate code for use from Java, SWIG has to be told which class/type to use as the template parameter. The SWIG directive %template is used for this.
85
86 <h2>A sample Java program</h2>
87
88 Click <a href="runme.java">here</a> to see a Java program that calls the C++ functions from Java.
89
90 <h2>Notes</h2>
91 Use templated classes just like you would any other SWIG generated Java class. Use the classnames specified by the %template directive.
92
93 <blockquote>
94 <pre>
95 vecdouble dv = new vecdouble(1000);
96 dv.setitem(i, 12.34));
97 </pre>
98 </blockquote>
99
100 <hr>
101 </body>
102 </html>