Q: Part of an API that I'm wrapping goes something like this:
struct A {}; struct B { void add( A* ); } where B::add() takes ownership of the pointer passed to it.
However:
a = mod.A() b = mod.B() b.add( a ) del a del b # python interpreter crashes # later due to memory corruption.
Even binding the lifetime of a to b via with_custodian_and_ward
doesn't prevent the python object a from ultimately trying to delete the
object it's pointing to. Is there a way to accomplish a 'transfer-of-ownership'
of a wrapped C++ object?
--Bruce Lowery
Yes: Make sure the C++ object is held by auto_ptr:
class_<A, std::auto_ptr<A> >("A") ... ;
Then make a thin wrapper function which takes an auto_ptr parameter:
void b_insert(B &b, std::auto_ptr<A> a) { b.insert(a.get()); a.release(); }
Wrap that as B.add. Note that pointers returned via manage_new_object
will also be held by auto_ptr
,
so this transfer-of-ownership will also work correctly.