I\'ve recently started using the Python/C API to build modules for Python using C code. I\'ve been trying to pass a Python list of numbers to a C function without success:
This example will show you how to
double
double
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
Would this do to properly free memory?
PyObject *res;
res = Py_BuildValue("i", _asdf(pr, pr_length));
free(pr);
return res;