Boost.Python.ArgumentError: python str not converted to std::string

霸气de小男生 提交于 2019-12-12 10:51:37

问题


I get an error I can't make sense of trying to wrap a rather simple c++ class via Boost.Python. First, the class:

#include <boost/python.hpp>
#include <boost/shared_ptr.hpp>
#include <vector>
#include <string>

class token {
    public:
    typedef boost::shared_ptr<token> ptr_type;

    static std::vector<std::string> empty_context;
    static std::string empty_center;

    token(std::string& t = empty_center,
            std::vector<std::string>& left = empty_context,
            std::vector<std::string>& right = empty_context)
        : center(t), left_context(left), right_context(right) {}
    virtual ~token(void)  {}  

    std::vector<std::string> left_context;
    std::vector<std::string> right_context;
    std::string center;
};

std::string token::empty_center;
std::vector<std::string> token::empty_context;

exposed to python via

BOOST_PYTHON_MODULE(test) {
    namespace bp = boost::python;
    bp::class_<token, token::ptr_type>("token")
    .def(bp::init<std::string&, bp::optional<std::vector<std::string>&,
            std::vector<std::string>&> >())
    ;   
}

then, when trying to use it in python:

Python 2.7.2 (default, Aug 19 2011, 20:41:43) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from test import token
>>> word = 'aa'
>>> t = token(word)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
Boost.Python.ArgumentError: Python argument types in
    token.__init__(token, str)
did not match C++ signature:
    __init__(_object*, std::string {lvalue})
    __init__(_object*, std::string {lvalue}, std::vector<std::string,     std::allocator<std::string> > {lvalue})
    __init__(_object*, std::string {lvalue}, std::vector<std::string,     std::allocator<std::string> > {lvalue}, std::vector<std::string, std::allocator<std::string>     > {lvalue})
    __init__(_object*)
>>> 

Can anyone point me to where this comes from? Shouldn't Boost.Python take care of converting python's str to std::string?

Versions of software/libraries involved:

Boost version: 1.46.1
Python version: 2.7.2
Compiler: g++ (SUSE Linux) 4.6.2
Makefile generation: cmake version 2.8.6
Make: GNU Make 3.82

回答1:


Your parameter type is std::string &, a modifiable reference to std::string. Python strings are immutable, so can't be converted to a modifiable reference. Your parameter type should be const std::string &.



来源:https://stackoverflow.com/questions/12277708/boost-python-argumenterror-python-str-not-converted-to-stdstring

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