Creating a PyObject* from a C double*

Joze joze_storme at yahoo.com
Sun Apr 13 15:10:56 EDT 2003


Exactly what i was looking for. Thanks a lot !!

Is there any way to avoid copying the array element by element and
simply pass a pointer to it?

Thanks again.
Joe.

Alex Martelli <aleax at aleax.it> wrote in message news:<YJ9ma.6928$LB6.196819 at news1.tin.it>...
> Joze wrote:
> 
> > Hi,
> > 
> > As part of a Python extension, i have an array of doubles created in a
> > C function, which should return a corresponding PyObject* to Python.
> > The array is meant to be used by Numeric/numarray, but apparently, the
> > C function cannot directly return a PyArrayObject*.
> 
> It can _after casting the pointer_ -- is that what's blocking you?
> 
> 
> > I have tried PyArray_FromDims(), PyArray_FromDimsAndData() but i can't
> 
> Those should only be used for static arrays -- ones that never will
> be deallocated; it's unlikely that's what you want.
> 
> > seem to get it right. Can anyone tell me how this works? I'd be most
> > grateful.
> 
> Here's a tiny working example just hacked together:
> 
> 
> #include <Python.h>
> #include <Numeric/arrayobject.h>
> 
> static PyObject*
> tiny(PyObject* self, PyObject* args)
> {
>     PyArrayObject* parr;
>     int dims[1];
>     int i;
>     double xx[] = {1.0, 2.3, 4.5, 6.7, 8.9};
>     double *data;
> 
>     dims[0] = 5;
>     parr = (PyArrayObject*) PyArray_FromDims(1, dims, 'd');
>     if(!parr) return 0;
> 
>     data = (double*) parr->data;
>     for(i=0; i<5; ++i)
>         data[i] = xx[i];
> 
>     return PyArray_Return(parr);
> }
> 
> static PyMethodDef tinyMethods[] = {
>     {"tiny", tiny, METH_VARARGS, "example"},
>     {0}
> };
> 
> void
> inittiny(void)
> {
>     Py_InitModule("tiny", tinyMethods);
>     import_array();
> }
> 
> anf after a python setup.py install with the obvious setup.py,
> 
> [alex at lancelot pronu]$ python2.2 -c 'import tiny; print tiny.tiny()'
> array([1.0, 2.2999999999999998, 4.5, 6.7000000000000002, 
> 8.9000000000000004], 'd')
> [alex at lancelot pronu]$
> 
> 
> Alex




More information about the Python-list mailing list