[C++-sig] Retrieving lvalues using custom converters (numpy 1-D converters attached)
Ravi
lists_ravi at lavabit.com
Wed Oct 1 23:22:18 CEST 2008
On Tuesday 30 September 2008 19:50:36 Ralf W. Grosse-Kunstleve wrote:
> > void do_something( boost::python::object &obj )
> > {
> > array_t a = boost::python::extract<array_t>( obj );
> > ...
> > }
>
> If the above works, this should work, too:
>
> void do_something( array_t a ) { ... }
That is very insightful and works very well for my application; more below.
[snip]
> FWIW:
> In my own code, I have an array ref<> type, which give you the .begin()
> and .size(), but not any of the functions that change the size of the
> array. I have custom converters from the main (reference-counted) array
> type to ref<>, which I can pass via
> ref<> const&
> and I can still modify the array elements.
Attached is some code then that could be useful to you. The following creates
a storage array that references a numpy array. Copies of this storage class
still point to the same underlying numpy array (whose reference count is
increased). The way to use this is as part of a ublas array:
typedef ublas::vector<double,numpy_storage_array<double> > array_t;
This class handles non-contiguous arrays; resizing is also allowed, subject to
the caveat that iterators are invalidated by resizing. The main limitation is
that only vectors are supported, i.e., no matrices. Matrix support would be
very simple to add but I haven't needed that for my application. As a usage
note, you would need to register the converters using the non-templated
registration functions provided in your extension module.
Note that all basic types supported by numpy are supported here as well; no
object arrays though! Comments welcome.
Regards,
Ravi
-------------- next part --------------
A non-text attachment was scrubbed...
Name: numpy.h
Type: text/x-chdr
Size: 15845 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/cplusplus-sig/attachments/20081001/c4a1bcc3/attachment.h>
More information about the Cplusplus-sig
mailing list