[C++-sig] how to wrap getter returning shared_ptr<T>

Langston, Matthew David langston at SLAC.Stanford.EDU
Tue Dec 10 01:09:24 CET 2002


How do I wrap a C++ member function that returns a shared_ptr? Here is an example of what I want to do:

class Bar
{
private:
    std::string m_message;
public:
    Bar() { m_message = "Bar: Hello, world"; }
    std::string get_Message() { return m_message; }
};

class Foo
{
private:
    shared_ptr<Bar> m_bar;
public:
    Foo() : m_bar( new Bar() ) {}
    shared_ptr<Bar> get_Bar() const { return m_bar; }
};


BOOST_PYTHON_MODULE(PyTest)
{
    class_< Bar > ( "Bar" ).add_property ("message", &Bar::get_Message);
    class_< Foo > ( "Foo" ).add_property ("bar"    , &Foo::get_Bar );
}


This code compiles and links fine, but when I try to access Foo::get_Bar from python I get the python error message " TypeError: bad argument type for built-in operation". This is the python script I used:


foo = Foo()
print foo.bar.message


I naively expected Boost.Python to just "do the right thing" w.r.t. a member function returning a boost::shared_ptr. What am I doing wrong?

Warmest regards, Matt

--
Matthew D. Langston
SLD, Stanford Linear Accelerator Center
langston at SLAC.Stanford.EDU





More information about the Cplusplus-sig mailing list