Numeric - extending with C

Jesper Olsen jolsen at mailme.dk
Wed Jan 16 13:15:12 EST 2002


Today I downloaded and installed Numeric 20.3 from sourceforge.
I installed it from source and have used it with python 2.1.1

Now I want to write and extention module. 
The documentation for how to do this is is not hard to read.

http://www.pfdubois.com/numpy/html2/numpy-13.html#pgfId-36640

But is it up to date?

I wrote a small C-extention module (see below), "mytest", 
which implements two functions:

mytest.get_array() - which builds and returns a Numeric array
mytest.pass_array() - which takes a Numeric array as argument

I get a segmentation error when I try to call these functions from python:

>>> import Numeric
>>> import mytest
>>> a=Numeric.array([1,2,3], "float")
>>> print a
[ 1. 2. 3.]
>>> mytest.pass_array(a)

likewise

>>> a=get_array()

also creates a segmentation fault.

Has anyone tried to do this? 

Cheers
Jesper



#include "Python.h"
#include "arrayobject.h"          /* from python Numeric */

static PyObject * mytest_get_array
(
    PyObject *self,
    PyObject *args
)
{
    int i;
    int dims[1];
    PyArrayObject* array;
    float *frame;

    dims[0]=3;
    printf("dims[0]=%d\n", dims[0]);

    array=PyArray_FromDims(1, dims, PyArray_FLOAT);
    if (array==NULL) return NULL;

    frame = (float*) array->data;

    for (i=0; i<3; i++)
        frame[i]=1.0;

    return PyArray_Return(array);
} /* mytest_get_frame */


static PyObject * mytest_pass_array
(
    PyObject *self,
    PyObject *args
)
{
    PyObject *input;
    PyArrayObject *array;
    float* frame;
    int i;

    if (!PyArg_ParseTuple(args, "O", &input)) return NULL;
    array=(PyArrayObject *) PyArray_ContiguousFromObject(input, PyArray_FLOAT, 
                                                         3, 3
                                                        );
    if (array==NULL) return NULL;

    frame=(float*) array->data;

    printf("Array Size=%d\n", array->dimensions[0]);
    for (i=0; i<3; i++)
        printf("%f ", frame[i]);
    printf("\n");

    Py_DECREF(array);
     
    Py_INCREF(Py_None);
    return Py_None;
} /* mytest_fsg_decoder_step */


static PyMethodDef mytestMethods[] =
{
    {"pass_array", mytest_pass_array,               METH_VARARGS},
    {"get_array", mytest_get_array, METH_VARARGS},
    {NULL, NULL, 0, NULL}               /* Sentinel */
};


void initmytest(void)
{
    PyObject *m = Py_InitModule("mytest", mytestMethods);    
}



More information about the Python-list mailing list