回首忆惘然
我正在使用以下代码将其公开std::pair<>为Python元组:#include <boost/python.hpp>namespace py = boost::pythontemplate<typename T1, typename T2>struct PairToPythonConverter { static PyObject* convert(const std::pair<T1, T2>& pair) { return py::incref(py::make_tuple(pair.first, pair.second).ptr()); }};template<typename T1, typename T2>struct PythonToPairConverter { PythonToPairConverter() { py::converter::registry::push_back(&convertible, &construct, py::type_id<std::pair<T1, T2> >()); } static void* convertible(PyObject* obj) { if (!PyTuple_CheckExact(obj)) return 0; if (PyTuple_Size(obj) != 2) return 0; return obj; } static void construct(PyObject* obj, py::converter::rvalue_from_python_stage1_data* data) { py::tuple tuple(py::borrowed(obj)); void* storage = ((py::converter::rvalue_from_python_storage<std::pair<T1, T2> >*) data)->storage.bytes; new (storage) std::pair<T1, T2>(py::extract<T1>(tuple[0]), py::extract<T2>(tuple[1])); data->convertible = storage; }};template<typename T1, typename T2>struct py_pair { py::to_python_converter<std::pair<T1, T2>, PairToPythonConverter<T1, T2> > toPy; PythonToPairConverter<T1, T2> fromPy;};在我的main内BOOST_PYTHON_MODULE(),然后可以使用例如py_pair<int, int>();暴露一对整数。