SWIG/python array inside structure

The easiest way to do this is to wrap your arrays inside a struct, which can then provide extra methods to meet the “subscriptable” requirements. I’ve put together a small example. It assumes you’re using C++, but the equivalent C version is fairly trivial to construct from this, it just requires a bit of repetition. … Read more

SWIG interfacing C library to Python (Creating ‘iterable’ Python data type from C ‘sequence’ struct)

The simplest solution to this is to implement __getitem__ and throw an IndexError exception for an invalid index. I put together an example of this, using %extend and %exception in SWIG to implement __getitem__ and raise an exception respectively: %module test %include “exception.i” %{ #include <assert.h> #include “test.h” static int myErr = 0; // flag … Read more

SWIG (v1.3.29) generated C++ to Java Vector class not acting properly

The appropriate base type for wrapping std::vector in Java is java.util.AbstractList. Using java.util.Vector as a base would be odd because you’d end up with two sets of storage, one in the std::vector, and one in the java.util.Vector. The reason SWIG doesn’t do this for you though is because you can’t have AbstractList<double> in Java, it … Read more

SWIG interface to receive an opaque struct reference in Java through function argument

At the most basic level you can make code that works using the cpointer.i part of the SWIG library to allow a direct “pointer to pointer” object to be created in Java. For example given the header file: #include <stdlib.h> typedef struct sp_session sp_session; typedef struct {} sp_session_config; typedef int sp_error; inline sp_error sp_session_create(const sp_session_config … Read more

Generating Java interface with SWIG

You can achieve what you’re looking for with SWIG+Java using “Directors“, however it’s not quite as straightforward mapping from the C++ abstract classes onto Java as you might hope. My answer therefore is split into three parts – firstly the simple example of implementing a C++ pure virtual function in Java, secondly an explanation of … Read more