Creating a PyObject* from a C double*

Alex Martelli aleax at
Sun Apr 13 11:03:52 CEST 2003

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"},

    Py_InitModule("tiny", tinyMethods);

anf after a python install with the obvious,

[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]$


More information about the Python-list mailing list