2012-09-05 55 views
3

我收到一個錯誤,我無法理解嘗試通過Boost.Python包裝一個相當簡單的C++類。 首先,類:Boost.Python.ArgumentError:python str未轉換爲std :: string

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

通過

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 

回答

8

你的參數類型是std::string &,可修改參照std::string。 Python字符串是不可變的,所以不能轉換爲可修改的引用。你的參數類型應該是const std::string &

+0

非常感謝你,這是它一直試圖讓這個轉換一段時間...(只要讓我這樣做就會接受這個答案) – tjanu