Question

While attempting to read a Python list filled with float numbers and to populate real channels[7] with their values (I'm using F2C, so real is just a typedef for float), all I am able to retrieve from it are zero values. Can you point out the error in the code below?

static PyObject *orbital_spectra(PyObject *self, PyObject *args) {
  PyListObject *input = (PyListObject*)PyList_New(0);
  real channels[7], coefficients[7], values[240];
  int i;

  if (!PyArg_ParseTuple(args, "O!", &PyList_Type, &input)) {
    return NULL;
  }
  for (i = 0; i < PyList_Size(input); i++) {
    printf("%f\n", PyList_GetItem(input, (Py_ssize_t)i)); // <--- Prints zeros
  }
//....
}
Was it helpful?

Solution

PyList_GetItem will return a PyObject*. You need to convert that to a number C understands. Try changing your code to this:

printf("%f\n", PyFloat_AsDouble(PyList_GetItem(input, (Py_ssize_t)i)));

OTHER TIPS

Few things I see in this code.

  1. You leak a reference, don't create that empty list at the beginning, it's not needed.
  2. You don't need to cast to PyListObject.
  3. PyList_GetItem returns a PyObject, not a float. Use PyFloat_AsDouble to extract the value.
  4. If PyList_GetItem returns NULL, then an exception has been thrown, and you should check for it.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top