c++ - Boost.Python.ArgumentError: python str 未转换为 std::string

标签 c++ boost boost-python

我收到一个错误,我无法理解尝试通过 Boost.Python 包装一个相当简单的 c++ 类。 一、类:

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

通过 python 暴露

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>&> >())
    ;   
}

然后,当尝试在 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*)
>>> 

谁能告诉我这是从哪里来的? Boost.Python 不应该负责将 python 的 str 转换为 std::string 吗?

涉及的软件/库版本:

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

最佳答案

您的参数类型是 std::string &,是对 std::string 的可修改引用。 Python 字符串是不可变的,因此不能转换为可修改的引用。您的参数类型应该是 const std::string &

关于c++ - Boost.Python.ArgumentError: python str 未转换为 std::string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12277708/

相关文章:

c++ - 没有匹配的函数可调用 'SDL_UpperBlit'

python - Boost.Python hello world教程: ImportError: ./hello.so: undefined symbol :_ZN3Num3setEf

c++ - 多线程和堆损坏

c++ - 如何在编译过程中编辑可执行文件而不更改其源代码?

c++ - boost IPC Message_Queue try_receive 抛出 interprocess_exception::library_error

c++ - Boost预处理器不扩展

python - 获取 Boost 中的参数列表 :Python function

c++ - 嵌入 Python : How to help the scripter?

c++,列出所有文件,Windows 上的 dirent.h

c++ - Boost是否曾用于受监管的项目(FDA,FAA)?