[C++-sig] Re: return value policy for returning same python object...
David Abrahams
dave at boost-consulting.com
Sun Jun 8 22:40:08 CEST 2003
"Milind Patil" <milind_patil at hotmail.com> writes:
> I have a scenario where a C++ method that performs inplace
> operation on the object is wrapped using boost python. I
> would like the corresponding python operation to result in the same object
> instead of a new python object. What is the return policy that
> will allow me to do that?
>
> eg. in Y_Wrapper class of some Y class...
>
> const Y&
> do_iadd (int other)
> {
> *this += Y_FromInt(other);
> return *this
> }
>
> BOOST_PYTHON_MODULE(hello)
> {
> ...
> .def("__iadd__", (const Y& Y_Wrapper::*) &do_iadd(int),
^^^^^^^^^^^^^^^^^^^^^^^
This C-style cast is dangerous, and in fact you got it wrong, which is
part of your problem. No cast should be needed.
> return_value_policy<>(??? which one ???))
> ...
> }
>
> in python...
>
> x = y.hello(0)
> a = x
> x += 1
>
> assert( a is x)
>
> I tried return_existing_object and the copy_... policies. Obviuosly,
> because they all return a new python object, that failed.
It's not obvious to me, though return_existing_object should be
unsafe I would expect it to work.
> Any pointers as to how I can get the desired behaviour?
Well, you are returning a reference to an internal object of the
Python Y object, so return_internal_reference seems entirely appropriate.
> (Notice I cannot do
> .def (self += other<int>())
> because there is no += in the Y class for Y& and int defined.)
Well, that *should* be easily fixable!
> Thanks,
> Milind
--
Dave Abrahams
Boost Consulting
www.boost-consulting.com
More information about the Cplusplus-sig
mailing list