Skip to content

Instantly share code, notes, and snippets.

@jansegre
Created February 18, 2017 02:57
Show Gist options
  • Save jansegre/f309772feee95188a2f5a00d6fdcaa5d to your computer and use it in GitHub Desktop.
Save jansegre/f309772feee95188a2f5a00d6fdcaa5d to your computer and use it in GitHub Desktop.
// cc -shared -fPIC -I/usr/include/python3.5m -O -g -o bar.so bar.c
#include "Python.h"
static PyObject* sum_list(PyObject* self, PyObject* args)
{
Py_ssize_t i, j, n;
long total = 0, value;
PyObject *item;
PyObject *list;
long *values;
if (!PyArg_ParseTuple(args, "O!", &PyList_Type, &list)) {
return NULL;
}
n = PyList_Size(list);
if (n < 0)
return NULL; /* Not a list */
values = (long *)malloc(sizeof(long) * n);
for (i = 0; i < n; i++) {
item = PyList_GetItem(list, i); /* Can't fail */
if (!PyLong_Check(item)) continue; /* Skip non-integers */
// cast to appropriate type
value = PyLong_AsLong(item);
if (value == -1 && PyErr_Occurred())
/* Integer too big to fit in a C long, bail out */
return NULL;
values[i] = value;
}
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
total += values[i] * values[j];
}
}
return Py_BuildValue("i", total);
}
/* Define functions in module */
static PyMethodDef bar_methods[] = {
{"bar", sum_list, METH_VARARGS, "Sum a list"},
{NULL, NULL, 0, NULL} /* Sentinel */
};
static struct PyModuleDef bar_mod =
{
PyModuleDef_HEAD_INIT,
"bar", /* name of module */
"", /* module documentation, may be NULL */
-1, /* size of per-interpreter state of the module, or -1 if the module keeps state in global variables. */
bar_methods
};
PyMODINIT_FUNC PyInit_bar(void)
{
return PyModule_Create(&bar_mod);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment