错误附加整数在c + + boost python列表 [英] error to append integer in c++ boost python list

查看:104
本文介绍了错误附加整数在c + + boost python列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这样做并不起作用

  #include< boost / python.hpp> 

namespace bp = boost :: python;

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

bp :: list points;

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

return 0;}

这就是append

编辑





<解决方案是:

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


解决方案

我认为你应该在导出的模块中使用 boost :: python :: list ,而不是直接从C ++程序。原因很简单: boost :: python :: list 是一个Python列表对象的包装器,使用它需要一个Python解释器,



这是一个工作示例:

$

b
$ b

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

编译此模块并运行 getlist 函数显示一切都按预期工作:

 > import listtest 
>>> print listtest.getlist()
[1,2,3]


I does this code and 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;}

解决方案

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]

这篇关于错误附加整数在c + + boost python列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆