error to append integer in c++ boost python list

痞子三分冷 提交于 2019-12-19 10:25:56

问题


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;}

回答1:


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]



回答2:


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

 points.append<int>(one);


来源:https://stackoverflow.com/questions/20672970/error-to-append-integer-in-c-boost-python-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!