[Tutor] Reading arrays through an extension module

sessile@in-gen.net sessile@in-gen.net
Wed, 03 Nov 1999 17:24:36 -0500


The code in question is attached at the bottom.  The first
function (get_float_arr), after some hacking, seems to be
working properly.  I take each element of the 1-D array and
append them into a PyList.  I'm not certain this is a good
approach but it gets me the numbers I want.

The second function, however, is incomplete.  I have not
been able to figure out how to build the 2-D array of floats
into a python object (list?).  Could someone show me an
efficent way to do this?  What if the array had arbitrarily
larger dimensions?

Also, should I be using Py_DECREF in these functions?

Thank you.
Dean.

====================

/*
 * Format of function (from documentation):
 * xxx_get_float_arr( int ARG,
 *                    float **tmp_float_arr,
 *                    int *len );
 *
 * This function takes a single argument (ARG) and returns a one
 * dimensional array of floats along with an int (len) which holds
 * the length of the array.
 */
static PyObject *
my_xxx_get_float_arr(self, args)
    PyObject *self;
    PyObject *args;
{
    int *ARG;
    int ii;
    int len;
    float *tmp_float_arr_c;
    PyObject *tmp_float_arr_py;
    
    if (!PyArg_ParseTuple(args, "i:get_float_arr", &ARG))
        return NULL;

    xxx_get_float_arr(ARG, &tmp_float_arr_c, &len)

    tmp_float_arr_py = PyList_New(0);
    for (ii=0; ii<len; ii++)
    {
        PyList_Append(tmp_float_arr_py, Py_BuildValue("f",
tmp_float_arr_c[ii]));
    }
    /* Py_DECREF(tmp_float_arr_py); */
    return Py_BuildValue("iN", len, tmp_float_arr_py);
}

/*
 * Format of function (from documentation):
 * xxx_get_float2_arr( int ARG,
 *                     float ***tmp_float_arr,
 *                     int *index1, int *index2 );
 *
 * This funtion takes a single argument (ARG) and returns a two
 * dimensional array of floats along with two ints holding the
 * dimensions of the array.
 */
static PyObject *
my_xxx_get_float2_arr(self, args)
    PyObject *self;
    PyObject *args;
{
    int *ARG;
    int index1, index2;
    float *tmp_float2_arr_c;
    PyObject *tmp_float2_arr_py;
    
    if (!PyArg_ParseTuple(args, "i:get_float2_arr", &ARG))
        return NULL;

    xxx_get_float2_arr(ARG, &tmp_float2_arr_c, &index1, &index2)

    return Py_BuildValue("ii", index1, index2);  /* incomplete */
}