I want to
- write a function
sum_listof sum a list in c, named sum_list.c - make the
sum_list.cfile to sum_list.so sum_list = ctypes.CDLL('./sum_list.so')result = sum_list.sum_list([1, 2, 3])
It raise error in step 4:
ctypes.ArgumentError: argument 1: : Don't know how to convert parameter 1
when I write a function in c which add two numbers, it works ok.
so, the point is i don't know how to pass a list (python object) to c.
sum_list.c
#define PY_SSIZE_T_CLEAN
#include <Python.h>
long sum_list(PyObject *list)
{
Py_ssize_t i, n;
long total = 0, value;
PyObject *item;
n = PyList_Size(list);
if (n < 0)
return -1; /* Not a list */
for (i = 0; i < n; i++) {
item = PyList_GetItem(list, i); /* Can't fail */
if (!PyLong_Check(item)) continue; /* Skip non-integers */
value = PyLong_AsLong(item);
if (value == -1 && PyErr_Occurred())
/* Integer too big to fit in a C long, bail out */
return -1;
total += value;
}
return total;
}
python code
from ctypes import CDLL
sum_list = CDLL('./sum_list.so')
l = [1, 2, 3]
sum_list.sum_list(l)
I expect the
varresult in my python code is6.
PyList_GetItem(list, i); /* Can't fail */is actually false. It can fail - especially if the list changes size for some reason during the iteration. It might be hard to deduce that it doesn't!