error to append integer in c++ boost python list

2019-02-19 23:33发布

I maked this code and it does not work

#include <boost/python.hpp>

namespace bp = boost::python;

int main(int argc, char **argv) {

bp::list points;

int one = 1;
int two = 2;
int three = 3;
points.append(one); #crach!!
points.append(two);
points.append(three);

return 0;}

which is the reason why "append" does not accept integers and directly which would be the correct way?

edited

the solution is this:

#include <boost/python.hpp>

namespace bp = boost::python;

int main(int argc, char **argv) {
    Py_Initialize(); //this part
bp::list points;

int one = 1;
int two = 2;
int three = 3;
points.append(one); #crach!!
points.append(two);
points.append(three);
    Py_Finalize(); //this part
return 0;}

2条回答
何必那么认真
2楼-- · 2019-02-19 23:47

From the documentation, it looks like a template method. So, you can try

 points.append<int>(one);
查看更多
forever°为你锁心
3楼-- · 2019-02-19 23:59

I think you are supposed to use boost::python::list from within the exported module, not from a C++ program directly. The reason for this is simple: boost::python::list is a wrapper around a Python list object and to work with it you need a Python interpreter which is not available when you try to operate on the list from your main method.

Here's a working example:

#include <boost/python.hpp>

namespace bp = boost::python;

bp::list getlist() {
  bp::list points;
  int one = 1;
  int two = 2;
  int three = 3;
  points.append(one);
  points.append(two);
  points.append(three);
  return points;
}

BOOST_PYTHON_MODULE(listtest) {
  using namespace boost::python;
  def("getlist", getlist);
}

Compiling this module and running the getlist function shows that everything works as expected:

>>> import listtest
>>> print listtest.getlist()
[1, 2, 3]
查看更多
登录 后发表回答