29 SWIG and Octave

Octave is a high-level language intended for numerical programming that is mostly compatible with MATLAB. More information can be found at Octave web site.

This chapter is intended to give an introduction to using the module. You should also read the SWIG documentation that is not specific to Octave. Also, there are a dozen or so examples in the Examples/octave directory, and hundreds in the test suite (Examples/test-suite and Examples/test-suite/octave).

29.1 Preliminaries

SWIG is regularly tested against the following versions of Octave: 3.8, 4.0, 4.2.

Every effort is made to maintain backward compatibility with older versions of Octave. This cannot be guaranteed however, as in recent times new Octave releases have required nontrivial updates to SWIG, which may break backward compatibility for older Octave versions against which SWIG is not regularly tested.

The SWIG runtime exports the function swig_octave_prereq() for checking the version of Octave.

29.2 Running SWIG

Let's start with a very simple SWIG interface file, example.i:

%module swigexample
%{
#include "example.h"
%}
int gcd(int x, int y);
extern double Foo; 

To build an Octave module when wrapping C code, run SWIG using the -octave option:

$ swig -octave -o example_wrap.cpp example.i 

The -c++ option is also required when wrapping C++ code:

$ swig -octave -c++ -o example_wrap.cpp example.i 

This creates a C++ source file "example_wrap.cpp". A C++ file is generated even when wrapping C code as Octave is itself written in C++ and requires wrapper code to be in the same language. The generated C++ source file contains the low-level wrappers that need to be compiled and linked with the rest of your C/C++ application (in this case, the gcd implementation) to create an extension module.

29.2.1 Command-line options

The swig command line has a number of options you can use, like to redirect its output. Use swig -help to learn about these. Options specific to the Octave module are:

$ swig -octave -help
...
Octave Options (available with -octave)
     -globals name - Set name used to access C global variables [default: 'cvar']
                     Use '.' to load C global variables into module namespace
     -opprefix str - Prefix str for global operator functions [default: 'op_']

The -globals option sets the name of the variable which is the namespace for C global variables exported by the module. The special name "." loads C global variables into the module namespace, i.e. alongside C functions and structs exported by the module. The -opprefix options sets the prefix of the names of global/friend operator functions.

29.2.2 Compiling a dynamic module

Octave modules are DLLs/shared objects having the ".oct" suffix. Building an oct file is usually done with the mkoctfile command (either within Octave itself, or from the shell). For example,

$ swig -octave -c++ -o example_wrap.cpp example.i
$ mkoctfile example_wrap.cpp example.c

where "example.c" is the file containing the gcd() implementation.

mkoctfile can also be used to extract the build parameters required to invoke the compiler and linker yourself. See the Octave manual and mkoctfile man page.

mkoctfile will produce "swigexample.oct", which contains the compiled extension module. Loading it into Octave is then a matter of invoking

octave:1> swigexample

29.2.3 Using your module

Assuming all goes well, you will be able to do this:

$ octave -q
octave:1> swigexample
octave:2> swigexample.gcd(4, 6)
ans =  2
octave:3> swigexample.cvar.Foo
ans =  3
octave:4> swigexample.cvar.Foo=4;
octave:5> swigexample.cvar.Foo
ans =  4 

29.3 A tour of basic C/C++ wrapping

29.3.1 Modules

The SWIG module directive specifies the name of the Octave module. If you specify "module swigexample", then in Octave everything in the module will be accessible under "swigexample", as in the above example. When choosing a module name, make sure you don't use the same name as a built-in Octave command or standard module name.

When Octave is asked to invoke swigexample, it will try to find the ".m" or ".oct" file that defines the function "swigexample". You therefore need to make sure that "swigexample.oct" is in Octave's search path, which can be specified with the environment variable "OCTAVE_PATH".

To load an Octave module, simply type its name:

octave:1> swigexample;
octave:2> gcd(4, 6)
ans =  2
octave:3> cvar.Foo
ans =  3
octave:4> cvar.Foo=4;
octave:5> cvar.Foo
ans =  4

Modules can also be loaded from within functions, even before being loaded in the base context. If the module is also used in the base context, however, it must first be loaded again:

octave:1> function l = my_lcm(a, b)
> swigexample
> l = abs(a*b)/swigexample.gcd(a, b);
> endfunction
octave:2> my_lcm(4, 6)
ans =  12
octave:3> swigexample.gcd(4, 6)
error: can't perform indexing operations for <unknown type> type
octave:3> swigexample;
octave:4> swigexample.gcd(4, 6)
ans =  2

29.3.2 Functions

Global functions are wrapped as new Octave built-in functions. For example,

%module swigexample
int fact(int n); 

creates a built-in function swigexample.fact(n) that works exactly like you think it does:

octave:1> swigexample.fact(4)
24 

29.3.3 Global variables

Global variables are a little special in Octave. Given a global variable:

%module swigexample
extern double Foo;

To expose variables, SWIG actually generates two functions, to get and set the value. In this case, Foo_set and Foo_set would be generated. SWIG then automatically calls these functions when you get and set the variable-- in the former case creating a local copy in the interpreter of the C variables, and in the latter case copying an interpreter variables onto the C variable.

octave:1> swigexample;
octave:2> c=swigexample.cvar.Foo
c =  3
octave:3> swigexample.cvar.Foo=4;
octave:4> c
c =  3
octave:5> swigexample.cvar.Foo
ans =  4

If a variable is marked with the %immutable directive then any attempts to set this variable will cause an Octave error. Given a global variable:

%module swigexample
%immutable;
extern double Foo;
%mutable;

SWIG will allow the reading of Foo but when a set attempt is made, an error function will be called.

octave:1> swigexample
octave:2> swigexample.Foo=4
error: attempt to set immutable member variable
error: assignment failed, or no method for `swig_type = scalar'
error: evaluating assignment expression near line 2, column 12 

It is possible to add new functions or variables to the module. This also allows the user to rename/remove existing functions and constants (but not linked variables, mutable or immutable). Therefore users are recommended to be careful when doing so.

octave:1> swigexample;
octave:2> swigexample.PI=3.142;
octave:3> swigexample.PI
ans =  3.1420 

29.3.4 Constants and enums

Because Octave doesn't really have the concept of constants, C/C++ constants are not really constant in Octave. They are actually just a copy of the value into the Octave interpreter. Therefore they can be changed just as any other value. For example given some constants:

%module swigexample
%constant int ICONST=42;
#define    SCONST      "Hello World"
enum Days{SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY};

This is 'effectively' converted into the following Octave code:

swigexample.ICONST=42
swigexample.SCONST="Hello World"
swigexample.SUNDAY=0
.... 

29.3.5 Pointers

C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no problem working with incomplete type information. Given a wrapping of the <file.h> interface: C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no problem working with incomplete type information. Given a wrapping of the <file.h> interface:

%module swigexample
FILE *fopen(const char *filename, const char *mode);
int fputs(const char *, FILE *);
int fclose(FILE *);

When wrapped, you will be able to use the functions in a natural way from Octave. For example:

octave:1> swigexample;
octave:2> f=swigexample.fopen("w", "junk");
octave:3> swigexample.fputs("Hello world", f);
octave:4> swigexample.fclose(f);

Simply printing the value of a wrapped C++ type will print its typename. E.g.,

octave:1> swigexample;
octave:2> f=swigexample.fopen("junk", "w");
octave:3> f
f =

{
  _p_FILE, ptr = 0x9b0cd00
} 

As the user of the pointer, you are responsible for freeing it, or closing any resources associated with it (just as you would in a C program). This does not apply so strictly to classes and structs (see below).

octave:1> swigexample;
octave:2> f=swigexample.fopen("not there", "r");
error: value on right hand side of assignment is undefined
error: evaluating assignment expression near line 2, column 2 

29.3.6 Structures and C++ classes

SWIG wraps C structures and C++ classes by using a special Octave type called a swig_ref. A swig_ref contains a reference to one or more instances of C/C++ objects, or just the type information for an object. For each wrapped structure and class, a swig_ref will be exposed that has the name of the type. When invoked as a function, it creates a new object of its type and returns a swig_ref that points to that instance. This provides a very natural interface. For example,

struct Point{
  int x, y;
};

is used as follows:

octave:1> swigexample;
octave:2> p=swigexample.Point();
octave:3> p.x=3;
octave:4> p.y=5;
octave:5> p.x, p.y
ans =  3
ans =  5 

In C++, invoking the type object in this way calls the object's constructor. swig_ref objects can also be acquired by having a wrapped function return a pointer, reference, or value of a non-primitive type.

The swig_ref type handles indexing operations such that usage maps closely to what you would have in C/C++. Structure members are accessed as in the above example, by calling set and get methods for C++ variables. Methods also work as expected. For example, code wrapped in the following way

class Point{
public:
  int x, y;
  Point(int _x, int _y) : x(_x), y(_y) {}
  double distance(const Point& rhs) {
    return sqrt(pow(x-rhs.x, 2)+pow(y-rhs.y, 2));
  }
  void set(int _x, int _y) {
    x=_x; y=_y;
  }
};

can be used from Octave like this

octave:1> swigexample;
octave:2> p1=swigexample.Poi