Unexpected extension module behaviour

John Machin sjmachin at lexicon.net
Wed May 24 23:29:02 EDT 2006


On 25/05/2006 12:09 PM, rimmer wrote:
> I'm writing an extension module in C in which I'm passing an array of
> floats from C to python.  The code below illustrates a simple C
> function designed to output an array of floats.
> 
[snip]
Couldn't restrain myself from reading further :-)

> 
> Then I write a wrapper function to pass the data back and forth between
> C and Python.
> 
> ----------------
> extTestWrapper.c
> ----------------
> 
> #include "/usr/include/python2.4/Python.h"
> #include <stdio.h>
> 
> // external declarations
> extern float *testArray(int);

Um, shouldn't that be "double", not "float"?

> 
> // Python wrapper for the testArray function
> PyObject *extTest_testArray(PyObject *self, PyObject *args) {
> 
>   double *nums;
>   int nsamp;
>   int i;
>   PyObject *pynums;
> 
>   if (!PyArg_ParseTuple(args, "i", &nsamp)) {
>     return NULL;
>   }
> 
>   // call the C function
>   nums = testArray(nsamp);
> 
>   // build a Python list object containing the array values
>   pynums = PyList_New(nsamp);

Test for errors!

>   for (i=0; i<=nsamp; i++){

Um, shouldn't that be "<", not "<="???
Note, you have the same problem in the C function.
"nsamp" is presumed in the absence of any docs to mean "number of 
samples". A caller passing in 5 expects to get 5 values, NOT 6.
But you are calling PyList_New with 5.

>     PyList_SetItem(pynums, i, PyFloat_FromDouble(nums[i]));

Given you are trying to stuff one extra item into the list, you should 
definitely test for errors here!!!

I suggest that you change this incrementally. First, just change the 
above line to test for errors. Then run it again so you can see what 
happens. Second, fix the other problems.

>   }
>   return Py_BuildValue("O", pynums);

Rather unnecessary; you can just return pynums.

[read before snipping :-)]


HTH,
John



More information about the Python-list mailing list