How to make a soft copy of a temporary Python object inside C++

Hello everybody, Maybe it is obvious but I could not figure out how to solve it yet.. Consider the A and B classes: Class B { public: int func() {return 1; } }; class A { public: void setB(B & b_instance) { b = &b_instance; // if in Python setB is called as: a=A(); a.setB(*B()*) where B() creates a temporary, // the b pointer becomes invalid after setB() function gets out of scope. } B * b; }; BOOST_PYTHON_MODULE(my_module) { _class<B>("B") .def("func",&B::func); _class<A>("A") .def("setB", &A::setB); } The function A::setB sets the b data member of class A. b is a pointer to an object of class B. In Python I can use: a=A() b=B() a.setB(b) that's ok since 'b' exists as long as 'a', which could be dangerous. Things get worse when in Python I write: a=A() a.setB(B()) because the pointer b in class A gets invalid when the setB function gets out of scope. So, how can I avoid Python for destroying the temporary and keep the object alive in C++? Does it have anything to do with the object ownership? Is there a way to change the ownership? Can I make a soft copy of the b_instance object inside the setB function? so it would increase the object counter and keep it alive and consequently the b pointer will not get invalid. I want to avoid making a deep copy. Thanks in advance. Raul Durand

On Tue, Dec 7, 2010 at 9:06 AM, Raul Durand <raul.durand@gmail.com> wrote:
So, how can I avoid Python for destroying the temporary and keep the object alive in C++? Does it have anything to do with the object ownership? Is there a way to change the ownership?
See with_custodian_and_ward in the docs: http://www.boost.org/doc/libs/1_45_0/libs/python/doc/tutorial/doc/html/pytho... http://www.boost.org/doc/libs/1_45_0/libs/python/doc/v2/with_custodian_and_w... HTH, -- Dave Abrahams BoostPro Computing http://www.boostpro.com

Thanks Dave, It worked nicely. I just did: class_<A>("A") .def("setB", &A::setB, with_custodian_and_ward<1,2>()); Cheers, Raul Durand

On Tue, Dec 7, 2010 at 1:31 PM, Raul Durand <raul.durand@gmail.com> wrote:
Thanks Dave,
It worked nicely. I just did:
class_<A>("A") .def("setB", &A::setB, with_custodian_and_ward<1,2>());
Cheers,
glad to help! -- Dave Abrahams BoostPro Computing http://www.boostpro.com
participants (2)
-
Dave Abrahams
-
Raul Durand