Boost::Python Reference Counting

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Boost::Python Reference Counting

laan
This post has NOT been accepted by the mailing list yet.
Hi,

I'm having issues with Boost::Python objects that contain a reference to a c++ object:

--- C++ code ----

#include <boost/python.hpp>

struct Container;

struct Element
{
    Element(const Container * c) : _container(c) { }
    std::string name() const;
    const Container * _container;
};

struct Container
{
    Container(const std::string & s) : _string(s) { }
   
    Element getElement()
    {
        return Element(this);
    }
    std::string name() const
    {
        return this->_string;
    }
    std::string _string;
};

std::string Element::name() const
{
    return _container->name();
}

using namespace boost::python;

BOOST_PYTHON_MODULE(libkatya)
{
    class_<Element>("Element", no_init)
        .def("name", &Element::name)
        ;

    class_<Container>("Container", init<std::string>())
        .def("getElement", &Container::getElement)
        ;
}
--- Python Code ----------------------
container = test.Container("X")
elem = container.getElement()
del(container)
print(elem.name())

When calling elem.name(), it will reference the "container" object, which has been deleted, and I'm getting a segfault.

How can I make boost::python increment the reference counter of Container when an element containing a pointer to the Container is returned?

Loading...