blob: cf2b1337bdf009cbca8490a37306533f3bba5c7e (
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
|
<html>
<head>
<title>SWIG:Examples:go:template</title>
</head>
<body bgcolor="#ffffff">
<tt>SWIG/Examples/go/template/</tt>
<hr>
<H2>C++ template support</H2>
<p>
This example illustrates how C++ templates can be used from Go using
SWIG.
<h2>The C++ Code</h2>
Let's take a templated function and a templated class as follows:
<blockquote>
<pre>
/* File : example.h */
// Some template definitions
template<class T> T max(T a, T b) { return a>b ? a : b; }
template<class T> class vector {
T *v;
int sz;
public:
vector(int _sz) {
v = new T[_sz];
sz = _sz;
}
T &get(int index) {
return v[index];
}
void set(int index, T &val) {
v[index] = val;
}
#ifdef SWIG
%addmethods {
T getitem(int index) {
return self->get(index);
}
void setitem(int index, T val) {
self->set(index,val);
}
}
#endif
};
</pre>
</blockquote>
The %addmethods is used for a neater interface from Go as the
functions <tt>get</tt> and <tt>set</tt> use C++ references to
primitive types. These are tricky to use from Go as they end up as
pointers, which only work when the C++ and Go types correspond
precisely.
<h2>The SWIG interface</h2>
A simple SWIG interface for this can be built by simply grabbing the
header file like this:
<blockquote>
<pre>
/* File : example.i */
%module example
%{
#include "example.h"
%}
/* Let's just grab the original header file here */
%include "example.h"
/* Now instantiate some specific template declarations */
%template(maxint) max<int>;
%template(maxdouble) max<double>;
%template(vecint) vector<int>;
%template(vecdouble) vector<double>;
</pre>
</blockquote>
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 Go, SWIG has to be told which class/type to
use as the template parameter. The SWIG directive %template is used
for this.
<h2>A sample Go program</h2>
Click <a href="runme.go">here</a> to see a Go program that calls the
C++ functions from Go.
<h2>Notes</h2> Use templated classes just like you would any other
SWIG generated Go class. Use the classnames specified by the %template
directive.
<blockquote>
<pre>
vecdouble dv = new vecdouble(1000);
dv.setitem(i, 12.34));
</pre>
</blockquote>
<hr>
</body>
</html>
|