SWIG/Examples/java/template/

C++ template support

This example illustrates how C++ templates can be used from Java using SWIG.

The C++ Code

Let's take a templated function and a templated class as follows:
/* File : example.h */

// Some template definitions

template T max(T a, T b) { return  a>b ? a : b; }

template 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
};
The %addmethods is used for a neater interface from Java as the functions get and set use C++ references to primitive types. These are tricky to use from Java as they end up as a pointer in Java (Java long).

The SWIG interface

A simple SWIG interface for this can be built by simply grabbing the header file like this:
/* 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;
%template(maxdouble) max;
%template(vecint) vector;
%template(vecdouble) vector;
Note that SWIG parses the templated function max and templated class vector 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.

A sample Java program

Click here to see a Java program that calls the C++ functions from Java.

Notes

Use templated classes just like you would any other SWIG generated Java class. Use the classnames specified by the %template directive.
vecdouble dv = new vecdouble(1000);
dv.setitem(i, 12.34));