Thursday, January 3, 2019

Python C Extension

Say we want to create a module named "pal" with a function called "f1" to calculate the sum of all numbers. For example to calculate numbers in 5, it does the following:
1+ (1+2) + (1+2+3) + (1+2+3+4) + (1+2+3+4+5) = 35

Step 1. Create a file called "palmodule.c" :
#include <Python.h>
static PyObject * pal_f1(PyObject *self, PyObject *args) {
  int x;
  PyArg_ParseTuple(args, "i", &x);
  long sum = 0;
  for (int C=1; C<=x; ++C) {
    for (int c=1; c<C+1; ++c) {
        sum = sum + c;
      }
  }
  return Py_BuildValue("l", sum);
}

static PyMethodDef PalMethods[] = {
  {"f1", pal_f1, METH_VARARGS, "To calculate the sum of numbers"},
  {NULL, NULL}
};

static struct PyModuleDef palmodule = {
   PyModuleDef_HEAD_INIT,
   "pal",   /* name of module */
   "Module with Function f1", /* module documentation*/
   -1, /* size of per-interpreter state or -1 if module keeps state in global variables.*/
   PalMethods
};

PyMODINIT_FUNC PyInit_pal(void) {
    return PyModule_Create(&palmodule);
}

Step 2. Create a file called "setup.py"
from distutils.core import setup, Extension
setup (name='pal',  version='1.0',  ext_modules=[Extension('pal', ['palmodule.c'])])         

Step 3. Install the extension using the following command:
sudo python3 setup.py install

Step 4. Now open the python3 interpreter and do the following:
>>>  from pal import f1
>>> f1(5)
35

No comments:

Post a Comment