PageRenderTime 25ms CodeModel.GetById 19ms app.highlight 2ms RepoModel.GetById 1ms app.codeStats 0ms

/trunk/Examples/go/template/index.html

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