[C++-sig] Automatic type conversion again

Roman Yakovenko roman.yakovenko at gmail.com
Wed May 9 06:48:52 CEST 2007


On 5/9/07, Albert Strasheim <fullung at gmail.com> wrote:
> Hello all
>
> Referring to Roman's excellent guide here:
>
> http://www.language-binding.net/pyplusplus/troubleshooting_guide/automatic_conversion/automatic_conversion.html
>
> Is there any way to allow conversion of PyObject* when passing to
> functions that expect references or pointers? In Roman's code he
> explicitly checks that doing this throws a TypeError:
>
> http://www.language-binding.net/pyplusplus/troubleshooting_guide/automatic_conversion/test.py.html
>
> e.g.
>
> self.failUnlessRaises( TypeError, tuples.test_triplet_ref_110, (1,1,0) )
>
> I can do this with SWIG typemaps, but SWIG doesn't seem to have a
> built-in equivalent for return_internal_reference or
> with_custodian_and_ward_postcall, so I'd like to stick to using
> Boost.Python if at all possible.

Memory management is pretty good reason to stick with Boost.Python.

The short answer - you cannot, the long answer - I believe it is
possible to find acceptable solution to the problem ( may be not ).

I could be wrong! You cannot, because an automatic conversion creates
temporal object, so the changes you do to it in the function cannot be
propagated to Python.

There are few possible work around.

The first on is to use decorators.

Every relevant exported function should have a decorator, which will
normalize argument types.

Explanation: Lets say your function takes YourArray*, while user gave
you an instance of ItsArray type as argument. You can create new
function that will create new YourArray instance from ItsArray. You
can define it as:

boost::python::object Its2YourArrayConverter( boost::python::object );

Also you create new YourArray instance, it doesn't necessary means
that you copy array content. You can use call policies to bind between
objects ( return and argument ) life time.

Thus you don't use "automatic conversion".

Using Python magic you can apply this decorator on every relevant function.

HTH

-- 
Roman Yakovenko
C++ Python language binding
http://www.language-binding.net/



More information about the Cplusplus-sig mailing list