【发布时间】:2020-01-25 10:41:17
【问题描述】:
我想使用 boost python 创建从 std::vector 到 Python 列表的自定义转换。为此,我遵循to_python_converter 方法。我使用了典型的转换器结构,即
template <class T, bool NoProxy = true>
struct vector_to_list {
static PyObject* convert(const std::vector<T>& vec) {
typedef typename std::vector<T>::const_iterator const_iter;
bp::list* l = new boost::python::list();
for (const_iter it = vec.begin(); it != vec.end(); ++it) {
if (NoProxy) {
l->append(boost::ref(*it));
} else {
l->append(*it);
}
}
return l->ptr();
}
static PyTypeObject const* get_pytype() { return &PyList_Type; }
};
我可以在很多情况下成功使用它,但它不适用于std::vector<double>。这就是我在我的 boost python 模块中声明这种转换的方式:
BOOST_PYTHON_MODULE(libmymodule_pywrap) {
.
.
.
bp::to_python_converter<std::vector<double, std::allocator<double> >,
vector_to_list<double, false>, true>(); // this doesn't work
bp::to_python_converter<std::vector<Eigen::VectorXd,
std::allocator<Eigen::VectorXd> >,
vector_to_list<Eigen::VectorXd, false>, true>(); // this works well
}
我得到以下编译错误:
/usr/include/boost/python/object/make_instance.hpp:27:9: error: no matching function for call to ‘assertion_failed(mpl_::failed************ boost::mpl::or_<boost::is_class<double>, boost::is_union<double>, mpl_::bool_<false>, mpl_::bool_<false>, mpl_::bool_<false> >::************)’
BOOST_MPL_ASSERT((mpl::or_<is_class<T>, is_union<T> >));
^
/usr/include/boost/mpl/assert.hpp:83:5: note: candidate: template<bool C> int mpl_::assertion_failed(typename mpl_::assert<C>::type)
int assertion_failed( typename assert<C>::type );
^
/usr/include/boost/mpl/assert.hpp:83:5: note: template argument deduction/substitution failed:
/usr/include/boost/python/object/make_instance.hpp:27:9: note: cannot convert ‘mpl_::assert_arg<boost::mpl::or_<boost::is_class<double>, boost::is_union<double>, mpl_::bool_<false>, mpl_::bool_<false>, mpl_::bool_<false> > >(0u, 1)’ (type ‘mpl_::failed************ boost::mpl::or_<boost::is_class<double>, boost::is_union<double>, mpl_::bool_<false>, mpl_::bool_<false>, mpl_::bool_<false> >::************’) to type ‘mpl_::assert<false>::type {aka mpl_::assert<false>}’
BOOST_MPL_ASSERT((mpl::or_<is_class<T>, is_union<T> >));
有人明白这是怎么回事吗?
【问题讨论】:
-
为什么不使用
vector_indexing_suite? :class_<std::vector<double>>("vecDouble") .def(vector_indexing_suite<std::vector<double> >()); -
我知道这种方法,但我决定不遵循它,因为它不是 Pythonic。
-
同意,它不像 Pythonic 但它带有包装器,似乎需要一些努力才能获得类似的易用性。也许这个(stackoverflow.com/a/15940413/9238288)答案可能会给你一些信息。祝你好运!
标签: python c++ boost converters