[SciPy-user] Need very simple example showing how to return numpy array from C/C++ function

Jeremy Conlin jeremit0@gmail....
Fri Dec 28 18:07:59 CST 2007


On Dec 28, 2007 5:50 PM, Matthieu Brucher <matthieu.brucher@gmail.com>
wrote:

> To make your .i work, you have two things to do :
> - first initialize numpy :
> %{
> #define SWIG_FILE_WITH_INIT
> %}
> %include "numpy.i"
> %init %{
> import_array();
> %}
>
> Then result (which is $1 in the typemap) is in fact a wrapper around the
> vector, and to get it, you have to dereference it, so the typemap becomes :
> %typemap(out) std::vector<double> {
>     int length = $1.size();
>     $result = PyArray_FromDims(1, &length, PyArray_DOUBLE);
>     memcpy(PyArray_DATA($result),&((*(&$1))[0]),sizeof(double)*length);
> }
>

YEAH!!! Now it works!  Thanks a lot!

Now that it works, I wonder how this could be done without copying the data.
 Since a STL vector can also be accessed and treated like an array, could we
exploit this to avoid copying?  I tried using the function
PyArray_FromDimsAndData and passing a reference to the first element using
the same syntax as for memcpy, but I got an error similar to the one I
previously reported:

error: no match for 'operator*' in '*result'



>
> I think I will add this one to my blog, if nobody minds.

I think it would be great to have a simple example like this available to
the community.  A page on the wiki would probably be best.  I could create
such a page, but with my limited experience, I'm not sure I would be the
best person.  I couldn't explain why all the elements in the *.i file are
necessary.

Thanks,
Jeremy


>
> Matthieu
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://projects.scipy.org/pipermail/scipy-user/attachments/20071228/09d82efe/attachment.html 


More information about the SciPy-user mailing list