Can you SWIG a boost::optional<>?

boost, c#, c++, swig

Solution

Since SWIG doesn't understand boost types, typemaps have to be written. Here's a pair of typemaps for `boost::optional<int>`.

From Python, `None` or an integer can be passed into a function:

%typemap(in) boost::optional<int> %{
    if($input == Py_None)
        $1 = boost::optional<int>();
    else
        $1 = boost::optional<int>(PyLong_AsLong($input));
%}

A returned `boost::optional<int>` will be converted to a None or a Python integer:

%typemap(out) boost::optional<int> %{
    if($1)
        $result = PyLong_FromLong(*$1);
    else
    {
        $result = Py_None;
        Py_INCREF(Py_None);
    }
%}

Problem

I've been using SWIG successfully to build a wrapper interface to make my C++ libraries available in C#. Recently I exposed some `boost::optional<>` objects and SWIG is having problems with them. Is there a standard way to deal with this? Someone must have run into this before...

Original source