|
Boost Users : |
From: Daniel Paull (dlp_at_[hidden])
Date: 2002-11-07 21:53:39
Hi all,
I'm having trouble with some object lifetime issues using Boost Python
V2. Basically, I'm in a situation where both C++ and Python want to
delete the same object.
Below is a simple example of the scenario. Consider the two classes A
and B. An instance of A is passed to B via the setA() method. B then
assumes ownership of A and deletes it in it's destructor. NOTE: the
behaviour of the C++ code can not be changed currently.
-------------------------------------
class A
{
public:
A() {}
~A() {}
};
class B
{
public:
B() : m_a( 0 ) {}
~B(){ if ( m_a ) delete m_a; }
void setA( A* a ){ m_a = a; }
private:
A* m_a;
};
---------------------------------------
I have defined a python module thus, being sure to indicate the pointer
adoption by using the with_custodian_and_ward<> policy:
---------------------------------------
BOOST_PYTHON_MODULE( my_module )
{
class_< A >( "A" )
;
class_< B >( "B" )
.def( "setA", &B::setA, with_custodian_and_ward<1, 2>()
)
;
}
---------------------------------------
All is fine, and I can show that instances of B keep their instance of A
alive.
However, executing the python code:
--------------
a = A()
b = B()
b.setA()
--------------
results in "a" (or rather, the wrapped C++ object) being deleted twice.
I can get around this problem by using a free function "createA()" which
returns a new instance of "A" using the "return_existing_object" return
value policy, but this seems dangerous and can introduce a memory leak
if the user does this from python:
--------------
def makeLeak():
a = createA()
makeLeak()
--------------
Perhaps a new call policy is the solution, but I'm not sure how to
proceed. Has anyone solved this problem already?
Thanks in advance,
Daniel Paull
Development Lead
Fractal Technologies
57 Havelock Street
West Perth WA Australia 6005
PO Box 1675
West Perth WA Australia 6872
Phone: +61 8 9211 6064
Mobile: 0408 921 897
Email: Daniel.Paull_at_[hidden]
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net