[C++-sig] Boost::Python Reference Counting

Neal Becker ndbecker2 at gmail.com
Tue May 20 13:57:54 CEST 2014


laan wrote:

> 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?
> 
> 
> 
> 
> 
> --
> View this message in context:
> http://boost.2283326.n4.nabble.com/Boost-Python-Reference-Counting-tp4662504.html
> Sent from the Python - c++-sig mailing list archive at Nabble.com.

Usually if I need a c++ obj to hold onto a reference, I use boost::shared_ptr.  
boost::python knows how to interoperate between boost::shared_ptr and python ref 
counting.



More information about the Cplusplus-sig mailing list