swig Introduction to Typemaps Basic typemap - Python


Example

Given the following custom Boolean type we want to wrap:

typedef char MYBOOL;
#define TRUE 1
#define FALSE 0

A simple approach might be to write the following typemaps in our SWIG interface:

%typemap(in) MYBOOL %{
  // $input is what we got passed from Python for this function argument
  $1 = PyObject_IsTrue($input);
  // $1 is what will be used for the C or C++ call and we are responsible for setting it
%}

%typemap(out) MYBOOL %{
  // $1 is what we got from our C or C++ call
  $result = PyBool_FromLong($1);
  // $result is what gets given back to Python and we are responsible for setting it
%}

With these typemaps, SWIG will insert our code into the generated wrapper every time it sees a MYBOOL passed into or out of a function call.