Boost logo

Boost Users :

From: Bruce Lowery bruce_lowery_at_[hidden])
Date: 2003-01-10 16:50:31


I have a simple C++ class that I've wrapped using Boost/Python,
v1.29.0 (on Win 2K), and that has a simple accessor returning a const
ref to an internal string. In the python interpreter, the accessor
raises an exception (see below),whereas another access that returns a
copy of the string works. Could someone explain my mistake?

--bruce

------ Bar.cpp --------
#include <string>
class Bar
{
public:
        Bar( const std::string& s ) : m_s( s ) {}
        std::string get_s_copy() const { return m_s; }
        const std::string& get_s_ref() const { return m_s; }
        std::string m_s;
};
#include <boost/python.hpp>
using namespace boost::python;
BOOST_PYTHON_MODULE(Foo)
{
class_<Bar>( "Bar", init< const std::string& >( args("s") ) )
        .def( "get_s_copy", &Bar::get_s_copy )
        .def( "get_s_ref", &Bar::get_s_ref,
             return_internal_reference<>() )
        .def_readonly( "m_s", &Bar::m_s )
        ;
 }

----- Python session ----
Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import Foo
>>> bar = Foo.Bar("hello")
>>> bar.m_s
'hello'
>>> bar.get_s_copy()
'hello'
>>> bar.get_s_ref()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: bad argument type for built-in operation
>>>


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net