|
Boost : |
Subject: [boost] How to make a soft copy of a temporary Python object inside C++
From: Raul Durand (raul.durand_at_[hidden])
Date: 2010-12-07 09:06:38
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
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk