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

Jeremy Conlin jeremit0@gmail....
Fri Dec 28 12:58:23 CST 2007


On Dec 28, 2007 4:32 AM, Matthieu Brucher <matthieu.brucher@gmail.com>
wrote:

>
>
> 2007/12/28, Nathan Bell <wnbell@gmail.com>:
> >
> > On Dec 27, 2007 3:20 PM, Jeremy Conlin <jeremit0@gmail.com> wrote:
> > > I have a class member function that looks like this:
> > >
> > > std::vector<double> discretize(...);
> > >
> > > I would like to return a numpy array instead of a
> > std::vector<double>.  I
> > > could (of course) rewrite my function to return a pointer to the first
> > > element of an array if needed.  I am currently using SWIG for wrapping
> > my
> > > code for Python.
> > >
> > > I have searched far and wide for a simple example of how I should do
> > this.
> > > Everything I find is *far* too complicated for someone doing this for
> > the
> > > first time.  Does someone have a simple example they would like to
> > share?  I
> > > have the "Guide to Numpy"; it has lots of information about the
> > different
> > > functions, it doesn't have any examples.
> >
> > I use STL vectors for ouput in scipy.sparse.  See line 517 of:
> >
> > http://projects.scipy.org/scipy/scipy/browser/trunk/scipy/sparse/sparsetools/numpy.i
> >
> > For a STL vector<double> named myvec this should work:
> >
> > int length = myvec.size();
> > PyObject *obj = PyArray_FromDims(1, &length, PyArray_DOUBLE);
> > memcpy(PyArray_DATA(obj),&(myvec[0]),sizeof(double)*length);
> >
> > If you know the size of the output in advance, then you might follow
> > Matthieu's suggestion since a copy is not required.
> >
>
> You can then create a custom typemap with Nathan's code (not tested) :
> %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);
> %}
>


Thank you, that is beginning to make more sense to one inexperienced in
wrapping.  There is one error that I haven't been able to work around.

error: no match for 'operator[]' in 'result[0]'

This comes from the memcpy line, I guess.  It looks like it is getting mixed
up between the $1 and the $result.  Do I need to apply this typemap to avoid
this error or is it automatically applied because the type (double) is
specified?

Thanks again,
Jeremy
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://projects.scipy.org/pipermail/scipy-user/attachments/20071228/b0e27a80/attachment.html 


More information about the SciPy-user mailing list