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.
--------- extTest.c --------- #include <stdio.h> double *testArray(int nsamp) { double nums[10000]; int i; double cumdata = 0.0; printf("%d\n", nsamp); for (i=0; i<=nsamp; i++) { printf("%d\n", i); nums[i] = cumdata; cumdata += 0.5; printf("%f\n", nums[i]); } return nums; } 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); // 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); for (i=0; i<=nsamp; i++){ PyList_SetItem(pynums, i, PyFloat_FromDouble(nums[i])); } return Py_BuildValue("O", pynums); } // method table mapping names to wrappers static PyMethodDef extTestMethods [] = { {"testArray", extTest_testArray, METH_VARARGS}, {NULL, NULL} }; //module init function void initextTest() { Py_InitModule("extTest", extTestMethods); } I then run the following setup.py script using python setup.py install --install-lib=. -------------------------------------------------------------------------------------------- # setup.py for extTest from distutils.core import setup, Extension setup(name="extTest", version="0.0.1", ext_modules=[Extension("extTest", ["extTest.c", "extTestWrapper.c"])]) -------------------------------------------------------------------------------------------- The library builds and installs ok. When I invoke the testArray function, it appears to work correctly (the output is as expected). For example, import extTest a = extTest.testArray(5) yields the following output: 5 0 0.000000 1 0.500000 2 1.000000 3 1.500000 4 2.000000 5 2.500000 Exception exceptions.IndexError: 'list assignment index out of range' in 'garbage collection' ignored Fatal Python error: unexpected exception during garbage collection Aborted Here is where I'm stumped. I must be doing something wrong during the PyList_SetItem or the Py_BuildValue. Any ideas on fixing this problem ? Regards, Rimmer -- http://mail.python.org/mailman/listinfo/python-list