[C++-sig] ownership of C++ object extended in Python

Mark Williams mark at image-engine.com
Tue Mar 20 00:22:00 CET 2007


>>     virtual ~event_t_wrapper(){
>>         if (this->m_pyobj) {
>>             //Py_DECREF(this->m_pyobj);
>>             this->m_pyobj = 0;
>>         }
>>     }
>>
> 
> Many thanks for the solution - it appears to be working just fine. 
> However I'm wondering why the Py_DECREF line above is commented out?
> 

One other thing - it would appear that if I add a __del__ method to my 
Python class then its destructor IS getting called when the instance 
goes out of scope, even though my C++ class is keeping a reference to 
its holder.

When the C++ class eventually calls, via the wrapper, the virtual member 
function implemented in Python will this not lead to undefined 
behaviour, especially if this member function relies on any instance 
data? Why is it valid to call Py_INCREF only when the virtual member is 
called? Is there really no way of being able to do it from the wrapper's 
constructor?

What I have essentially is this:

class PythonDerived( CppBase ):

	def __init__(self):
		CppBase.__init__(self)

	def __del__(self):
		print("__del__")

	def func(self): #Override pure_virtual in CppBase
		print("PythonDerived.func")


def test():
	pd = PythonDerived()
	globalCppHolder.hold( pd )
	# "pd" goes out of scope here


 > test()
__del__

 > globalCppHolder.callFuncInAllHeldObjects()
PythonDerived.func

So "PythonDerived.func" gets called after the destructor.



Thanks again,
Mark

I'm wrapping CppBase as suggested in the example code you kindly sent.




More information about the Cplusplus-sig mailing list