00001 #ifndef BOOST_ADAPTBX_STD_PAIR_CONVERSION_H
00002 #define BOOST_ADAPTBX_STD_PAIR_CONVERSION_H
00003
00004 #include <boost/python/tuple.hpp>
00005 #include <boost/python/extract.hpp>
00006 #include <boost/python/to_python_converter.hpp>
00007
00008 namespace boost_adaptbx { namespace std_pair_conversions {
00009
00010 namespace detail {
00011 template <typename T, typename U>
00012 struct to_tuple
00013 {
00014 static PyObject* convert(std::pair<T,U> const& p) {
00015 using namespace boost::python;
00016 return incref(boost::python::make_tuple(p.first, p.second).ptr());
00017 }
00018
00019 static PyTypeObject const *get_pytype() { return &PyTuple_Type; }
00020 };
00021 }
00022
00023 template <typename T, typename U>
00024 struct to_tuple
00025 {
00026 to_tuple() {
00027 using namespace boost::python;
00028 to_python_converter<std::pair<T,U>, detail::to_tuple<T,U>
00029 #ifdef BOOST_PYTHON_SUPPORTS_PY_SIGNATURES
00030 , true
00031 #endif
00032 >();
00033 }
00034 };
00035
00036 template <typename T, typename U>
00037 struct from_tuple
00038 {
00039 from_tuple() {
00040 using namespace boost::python::converter;
00041 registry::push_back(&convertible,
00042 &construct,
00043 boost::python::type_id<std::pair<T,U> >()
00044 #ifdef BOOST_PYTHON_SUPPORTS_PY_SIGNATURES
00045 , get_pytype
00046 #endif
00047 );
00048 }
00049
00050 static const PyTypeObject *get_pytype() { return &PyTuple_Type; }
00051
00052 static void *convertible(PyObject *o) {
00053 using namespace boost::python;
00054 if (!PyTuple_Check(o) || PyTuple_GET_SIZE(o) != 2) return 0;
00055 return o;
00056 }
00057
00058 static void construct(
00059 PyObject *o,
00060 boost::python::converter::rvalue_from_python_stage1_data *data)
00061 {
00062 using boost::python::extract;
00063 using namespace boost::python::converter;
00064 PyObject *first = PyTuple_GET_ITEM(o, 0),
00065 *second = PyTuple_GET_ITEM(o, 1);
00066 void *storage =
00067 ((rvalue_from_python_storage<std::pair<T,U> >*) data)->storage.bytes;
00068 new (storage) std::pair<T,U>(extract<T>(first), extract<U>(second));
00069 data->convertible = storage;
00070 }
00071 };
00072
00073 template <typename T, typename U>
00074 struct to_and_from_tuple
00075 {
00076 to_and_from_tuple() {
00077 to_tuple<T,U>();
00078 from_tuple<T,U>();
00079 }
00080 };
00081
00082
00083 }}
00084
00085 #endif