Numeric - writing extentions

Jesper Olsen jolsen at mailme.dk
Wed Jan 16 11:17:06 EST 2002


Today I downloaded and installed Numeric-20.3 from sourceforge
- I installed it from source, and it seems to work ok (with python 2.1.1).

Now I want to write an extention where I use Numeric.array 

The documentation for how to do this is not hard to read:

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

But is it up to date?
I wrote an extention module called "mytest" (see below), with
two functions 

mytest.get_array() - creates and returns a numeric array
mytest.pass_array  - accepts a numeric array as parameter

However, I get a segmentation fault when I try to call these
functions from python:

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

likewise

a=mytest.get_array()

also results in a segmentation fault.

Has anyone tried this?

Cheers
Jesper

Here is the C code for the extention:

#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;

    printf("calling get_frame_ptr()\n");

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

    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