如何使用boost :: python将std :: pair暴露给python?

如何使用暴露std::pair给python boost::python?例如,当我公开时,vector<string>我只写:


class_<std::vector<std::string> >("StringVec")

    .def(vector_indexing_suite<std::vector<std::string> >())

;

但是我不知道如何处理std :: pair。


拉丁的传说
浏览 238回答 2
2回答

BIG阳

我找到了解决方案。暴露的最简单示例std::pair是:class_<std::pair<int, int> >("IntPair")&nbsp; &nbsp; .def_readwrite("first", &std::pair<int, int>::first)&nbsp; &nbsp; .def_readwrite("second", &std::pair<int, int>::second);

回首忆惘然

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

相关分类

Python