[C++-sig] Boost.Python: How do I handle object destruction of a Python-created object?

Niall Douglas s_sourceforge at nedprod.com
Thu Nov 24 14:16:22 CET 2011


Shouldn't you be wrapping a managed pointer to your C++ instance? 
That stages the destruction properly by keeping the virtual function 
table around long enough to call a virtualised destructor.

Search the archives of this mailing list. There are lots of examples.

Niall


On 24 Nov 2011 at 0:07, Adam Preble wrote:

> I'm using boost 1.47 on Windows Vista, with Visual Studio 2010.
> 
> My situation is something like this:
> 
> 1. I have a base interface in C++ to which I've exposed a wrapper in Python.
> 2. In the C++ source, I have a class that contains multiple instantiations
> of said interface.  We can call it Foo.  Foo has been wrapped too.
> 3. In Python, I've implemented this interface.
> 4. I have an instance of the object floating around that I created in
> Python, contained within a Foo instantiate in Python.
> 5. The code goes out of scope, and Foo's destructor starts.  Foo's
> destructor will try to delete its implementations of the interface.
> 6. Upon running into the Python implementation of the interface, we crash.
> 
> Actually, with gcc in Linux I don't see anything bad happen at all.  It
> isn't until I try this on Windows that all hell breaks loose.  What I've
> found with my code is that this isn't Visual Studio 2010's fault.  It's
> calling me out on something stupid that gcc/Linux let slide.  I think the
> fundamental question is: how I can get the resource freed through Python
> correctly?
> 
> If I let the Python class implementation go out of scope on its own, I
> don't see any problems.  Furthermore, Foo is content on its own.  It's the
> merging of the two that brings me problems.  Particularly, the program
> crashes when I try to delete the Python-instantiated object.  I'm not
> entirely surprised by this, but I have no real good way to try to tackle
> this problem.  I don't even have good, crisp source code to show the
> problem yet.  The code where this has happened has been running fine on
> Linux for awhile so I don't have an isolated case to post.  I can work
> towards that if I've confused everybody.
> 
> One last note.  I did put some test print statements in the virtual
> destructor I had written for the interface.  I do see that code does run,
> so I think it ultimately comes down to the memory freeing negotiated
> between Python and my C++ runtime.
> 


-- 
Technology & Consulting Services - ned Productions Limited.
http://www.nedproductions.biz/. VAT reg: IE 9708311Q. Company no: 
472909.





More information about the Cplusplus-sig mailing list