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

Ernie Lee tr.ernie.l at gmail.com
Mon Mar 9 21:26:30 CET 2015


Hello,


 I am working on adding Python binding to C++ project and run into the
following problem: For some reason Python tries to delete objects that are
still held by smart pointer instances in our C++ code.


 We are using std::shared_ptr for memory management and classes exposed
through Boost::Python have HeldType set to std::shared_ptr<…>. This problem
manifests itself in the following scenarios:


 - in Python i subclass C++ class, which acts as ‘callback’, and create an
instance of it and pass it to C++ code, where it is held in std::shared_ptr
instance. Python script itself does not use this callback object after that
point. When Python script terminates i receive memory error, which seems to
be triggered by attempting to double-free this callback object.


 - in Python i subclass C++ class, create an instance of it (call it ‘A')
and store it in container-like object (call it ‘B') (B is defined in C++
and exposed to Python). B stores shared_ptr to A. As soon as Python
execution point leaves current scope my object A gets deleted while B still
holds shared_ptr to A.


 It looks to me that ether i have a bug in my wrapping code (any idea what
this could be?) or in some cases Python disregards HeldType and tries to
determine object lifespan by its own means (in both cases from Python point
of view created object is no longer in scope so i am guessing thats why it
tries to delete it). If the latter is correct, any idea how to force Python
to use smart pointer class specified in HeldType?


 Thank you,

Ernie.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/cplusplus-sig/attachments/20150309/e716d783/attachment.html>


More information about the Cplusplus-sig mailing list