[C++-sig] Memory management in Boost.Python

Ernie Lee tr.ernie.l at gmail.com
Mon Mar 16 01:11:17 CET 2015


Hi Stefan,

  I tried to create minimal tests and it turned out that there might be two
separate issues here: one related to memory management and other to
subclassing C++ classes in Python (i will post the subclassing example in
separate mail).

  Running code below as-is works fine and i can see printed message
generated by ‘A’ class destructor. However commenting out line
‘reset_callback()’ in Python code will lead to a segfault and also no call
to ‘A’ class destructor occur. Thoughts?

  Thanks,


Ernie.


Python code: ————————
from callback2 import *

a1 = A()
a1.info()
set_callback(a1)
test_callback()
reset_callback()

C++ code: ——————————
include <iostream>
#include <boost/shared_ptr.hpp>
#include <boost/python.hpp>

class A
{
public:
virtual ~A() { std::cout << "A destructor for object: " << this <<
std::endl; }

virtual void info() { std::cout << "C++ A info for object" << this <<
std::endl; }
};

static boost::shared_ptr<A> current_callback;

void set_callback(boost::shared_ptr<A> a) {current_callback = a; }

void reset_callback() { current_callback = boost::shared_ptr<A>(); }

void test_callback()
{
std::cout << "test_callback: ";
if(current_callback) current_callback->info();
else std::cout << "Callback is NULL!" << std::endl;
}


BOOST_PYTHON_MODULE(callback2)
{
boost::python::class_<A, boost::shared_ptr< A >, boost::noncopyable>("A")
.def("info", &A::info)
;

boost::python::def("set_callback",   set_callback);
boost::python::def("reset_callback", reset_callback);
boost::python::def("test_callback",  test_callback);
}
————————————————


On Wed, Mar 11, 2015 at 12:01 AM, Stefan Seefeld <stefan at seefeld.name>
wrote:

> On 10/03/15 11:24 PM, Ernie Lee wrote:
> > Hi Stefan,
> >
> >   I updated my code so it now use 'boost::shared_ptr' class while
> > specifying the held-type and i got exactly the same errors (i guess
> > boost did recognize class even in different namespace).
> >
> >   Any other theories of what could be wrong? Could it be that Python
> > in some cases tries to manage memory directly, disregarding SP layer?
>
> In that case I suggest you narrow down the failure into a minimal test
> case and send that to the list. Otherwise this would be highly
> speculative and thus inefficient.
>
> Regards,
>         Stefan
>
> --
>
>       ...ich hab' noch einen Koffer in Berlin...
>
> _______________________________________________
> Cplusplus-sig mailing list
> Cplusplus-sig at python.org
> https://mail.python.org/mailman/listinfo/cplusplus-sig
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/cplusplus-sig/attachments/20150315/9de6efe3/attachment.html>


More information about the Cplusplus-sig mailing list