[C++-sig] easy method for converting boost::tuple to python tuple?
David Abrahams
dave at boost-consulting.com
Mon Jan 23 20:58:21 CET 2006
Grant Goodyear <grant at grantgoodyear.org> writes:
> I have a c++ function that returns boost::tuple<double, float, int>. From
> python I get the following when I try to access this function::
>
> No to_python (by-value) converter found for C++ type:
> boost::tuples::tuple<double, float, int, boost::tuples::null_type,
> boost::tuples::null_type, boost::tuples::null_type,
> boost::tuples::null_type, boost::tuples::null_type,
> boost::tuples::null_type, boost::tuples::null_type>
>
> Fair enough, I need to tell boost.python what to do. Google provides
> the following link:
> http://mail.python.org/pipermail/c++-sig/2002-July/001722.html
> which is a tad dated. Is there a simple way to tell boost.python
> how to perform the conversion?
http://www.boost.org/libs/python/doc/v2/to_python_converter.html
should set you on the right path.
// Untested!
#include <boost/python/tuple.hpp>
#include <boost/python/module.hpp>
#include <boost/python/refcount.hpp>
namespace python = boost::python;
namespace tuples = boost::tuples;
namespace my
{
template <class H, class T>
python::tuple tuple_to_python(tuples::cons<H,T> const& x)
{
return python::make_tuple(x) + my::tuple_to_python(x.tail);
}
python::tuple tuple_to_python(tuples::null_type)
{
return python::tuple();
}
template <class T>
struct tupleconverter
{
static PyObject* convert(T const& x)
{
return python::incref(my::tuple_to_python(x).ptr());
}
};
}
BOOST_PYTHON_MODULE(whatever)
{
to_python_converter<my_tuple_type, tupleconverter<my_tuple_type> >();
}
Something like this really should be in the library already, though,
shouldn't it?
--
Dave Abrahams
Boost Consulting
www.boost-consulting.com
More information about the Cplusplus-sig
mailing list