Passing a Python list to C function using the Python/C API
This example will show you how to
- Get the length of the list
- Allocate storage for an array of
double
- Get each element of the list
- Convert each element to a
double
- Store each converted element in the array
Here is the code:
#include "Python.h"
int _asdf(double pr[], int length) {
for (int index = 0; index < length; index++)
printf("pr[%d] = %f\n", index, pr[index]);
return 0;
}
static PyObject *asdf(PyObject *self, PyObject *args)
{
PyObject *float_list;
int pr_length;
double *pr;
if (!PyArg_ParseTuple(args, "O", &float_list))
return NULL;
pr_length = PyObject_Length(float_list);
if (pr_length < 0)
return NULL;
pr = (double *) malloc(sizeof(double *) * pr_length);
if (pr == NULL)
return NULL;
for (int index = 0; index < pr_length; index++) {
PyObject *item;
item = PyList_GetItem(float_list, index);
if (!PyFloat_Check(item))
pr[index] = 0.0;
pr[index] = PyFloat_AsDouble(item);
}
return Py_BuildValue("i", _asdf(pr, pr_length));
}
NOTE: White space and braces removed to keep code from scrolling.
Test program
import asdf
print asdf.asdf([0.7, 0.0, 0.1, 0.0, 0.0, 0.2])
Output
pr[0] = 0.700000
pr[1] = 0.000000
pr[2] = 0.100000
pr[3] = 0.000000
pr[4] = 0.000000
pr[5] = 0.200000
0
Addressing Concerns About Memory Leaks
People seem to be worried about the code not freeing the memory. This is just enough code to show how to convert the list to double. I wanted the code to be able to fit in the text box without scrolling, so it is not production code.