|
| 1 | +// Copyright Ralf W. Grosse-Kunstleve 2002-2004. Distributed under the Boost |
| 2 | +// Software License, Version 1.0. (See accompanying |
| 3 | +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) |
| 4 | + |
| 5 | +#include <boost/python/module.hpp> |
| 6 | +#include <boost/python/def.hpp> |
| 7 | +#include <boost/python/tuple.hpp> |
| 8 | +#include <boost/python/to_python_converter.hpp> |
| 9 | + |
| 10 | +namespace { // Avoid cluttering the global namespace. |
| 11 | + |
| 12 | + // Converts a std::pair instance to a Python tuple. |
| 13 | + template <typename T1, typename T2> |
| 14 | + struct std_pair_to_tuple |
| 15 | + { |
| 16 | + static PyObject* convert(std::pair<T1, T2> const& p) |
| 17 | + { |
| 18 | + return boost::python::incref( |
| 19 | + boost::python::make_tuple(p.first, p.second).ptr()); |
| 20 | + } |
| 21 | + }; |
| 22 | + |
| 23 | + // Helper for convenience. |
| 24 | + template <typename T1, typename T2> |
| 25 | + struct std_pair_to_python_converter |
| 26 | + { |
| 27 | + std_pair_to_python_converter() |
| 28 | + { |
| 29 | + boost::python::to_python_converter< |
| 30 | + std::pair<T1, T2>, |
| 31 | + std_pair_to_tuple<T1, T2> >(); |
| 32 | + } |
| 33 | + }; |
| 34 | + |
| 35 | + // Example function returning a std::pair. |
| 36 | + std::pair<int, int> |
| 37 | + foo() { return std::pair<int, int>(3, 5); } |
| 38 | + |
| 39 | +} // namespace anonymous |
| 40 | + |
| 41 | +BOOST_PYTHON_MODULE(std_pair_ext) |
| 42 | +{ |
| 43 | + using namespace boost::python; |
| 44 | + std_pair_to_python_converter<int, int>(); |
| 45 | + def("foo", foo); |
| 46 | +} |
0 commit comments