2 回答
TA贡献1859条经验 获得超6个赞
我找到了解决方案。暴露的最简单示例std::pair是:
class_<std::pair<int, int> >("IntPair")
.def_readwrite("first", &std::pair<int, int>::first)
.def_readwrite("second", &std::pair<int, int>::second);
TA贡献1847条经验 获得超11个赞
我正在使用以下代码将其公开std::pair<>为Python元组:
#include <boost/python.hpp>
namespace py = boost::python
template<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>();暴露一对整数。
添加回答
举报