如何导出std::

2024-09-24 22:29:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写申请书boost.python图书馆。我想把函数传递给python,它返回std::vector。我有点小麻烦:

inline std::vector<std::string> getConfigListValue(const std::string &key)
{
    return configManager().getListValue(key);
}

BOOST_PYTHON_MODULE(MyModule)
{
    bp::def("getListValue", getListValue);
}

当我从python调用该函数时,我得到:

^{pr2}$

我错过了什么?在


Tags: key函数stringreturn图书馆inlinemodulestd
3条回答

这是一个有点老的问题,但我发现,如果您明确要求按值返回,例如:

namespace bp = boost::python

BOOST_PYTHON_MODULE(MyModule)
{
    bp::def("getListValue", getListValue,
            bp::return_value_policy<bp::return_by_value>());
}      

而不是

^{pr2}$

Python为您进行转换(在编写这个答案时,我使用的是python2.7),不需要声明/定义转换器。在

@Tryskele公司

我使用以下实用程序函数从/到stl容器转换。平凡和函数说明了如何使用它们。我希望你能用它。在

#include <vector>
#include <boost/python.hpp>
#include <boost/python/object.hpp>
#include <boost/python/stl_iterator.hpp>

namespace bpy = boost::python;

namespace fm {

template <typename Container>
bpy::list stl2py(const Container& vec) {
  typedef typename Container::value_type T;
  bpy::list lst;
  std::for_each(vec.begin(), vec.end(), [&](const T& t) { lst.append(t); });
  return lst;
}

template <typename Container>
void py2stl(const bpy::list& lst, Container& vec) {
  typedef typename Container::value_type T;
  bpy::stl_input_iterator<T> beg(lst), end;
  std::for_each(beg, end, [&](const T& t) { vec.push_back(t); });
}

bpy::list sum(const bpy::list& lhs, const bpy::list& rhs) {
  std::vector<double> lhsv;
  py2stl(lhs, lhsv);

  std::vector<double> rhsv;
  py2stl(rhs, rhsv);

  std::vector<double> result(lhsv.size(), 0.0);
  for (int i = 0; i < lhsv.size(); ++i) {
    result[i] = lhsv[i] + rhsv[i];
  }
  return stl2py(result);
}

} // namespace fm

BOOST_PYTHON_MODULE(entry)
{
  // intended to be fast math's fast sum :)
  bpy::def("sum", &fm::sum);
}

你应该这样写一个转换器:

template<class T>
struct VecToList
{
    static PyObject* convert(const std::vector<T>& vec)
    {
        boost::python::list* l = new boost::python::list();
        for(size_t i = 0; i < vec.size(); i++) {
            l->append(vec[i]);
        }

        return l->ptr();
    }
};

然后在模块中注册:

^{pr2}$

相关问题 更多 >