如何公开返回变量向量的函数?

时间:2015-07-23 13:27:30

标签: python c++ boost vector boost-python

我正在寻找C++模块的一个小工作示例,该模块的方法返回variant vector并将其公开给Python(看起来像一个古老的问题,可以追溯到2004,但我找不到任何明确的答案。我已阅读thisthis等等,但仍无法找到解决方案。至于documentation,它似乎立即向读者提供大量信息。我想要的是一个微小的工作示例,其中一个微小的方法返回一个微小的向量。这就是我现在所拥有的:

#include <boost/variant.hpp>
#include <boost/python.hpp>
#include <vector>

using namespace std;
using namespace boost:python

typedef boost::variant<int> variant;
typedef vector<variant> vector;

class Some{
   private:
      int idx;
   public:
      Some(...){ ... } //not important
      vector MyMethod(){
          return vector{1};
      }
 };

BOOST_PYTHON_MODULE(some){
    class_<vector>("vector").def(vector_indexing_suite<vector, true>());
    class_<Some>("Some",
        init ... //not important
        .def("MyMethod",&Some::MyMethod);
}

如果我注释掉这个方法,我对结果共享库的编译,链接和使用没有任何问题。但是,如果有这样的方法返回一个向量,那么我会得到一堆错误。我想,我需要做一些额外的步骤,比如打鼓和做一些其他神奇的东西(或者一些数据类型转换等),但我不知道到底是什么步骤。

1 个答案:

答案 0 :(得分:3)

你应该为to_python_convertervariant,这样的事情应该有效:

#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
#include <Python.h>
#include <vector>
#include <boost/variant.hpp>

typedef boost::variant<int> number;
typedef std::vector<number> vector;

vector function()
{
   return vector{1};
}

struct number_to_object : boost::static_visitor<PyObject*>
{
   static result_type convert(number const& v)
   {
      return apply_visitor(number_to_object(), v);
   }

   template<typename T>
   result_type operator () (T const& v) const
   {
      return boost::python::incref(boost::python::object(v).ptr());
   }
};

void init_module() {}

BOOST_PYTHON_MODULE(pyexc_test)
{
   using namespace boost::python;

   class_<vector>("vector").def(vector_indexing_suite<vector, true>());

   to_python_converter<number, number_to_object>();
   implicitly_convertible<int, number>();

   def("function", function);
   def("init_module", init_module);
}