JeffLabonte
10/7/2019 - 6:02 PM

C Extension with Python 3

Notes taking on the subject of C extension with Python 3

Notes on C Extension with Python 3

Notes are taking on the video called Python3 Advanced Tutorial 9

Useful informations

  • PyArg_ParseTuple(args, format, ...)
    • Handle getting the arguments from Python
  • Py_BuildValue(format, ...)
    • Handles turning values into PyObject pointers
  • PyModule_Create(moduleDef)
    • Initialize the modules and wraps the method pointers using the module definitions
  • If you want your function to return nothing, return the Py_None value

PyMethodDef

  • The PyMethodDef structure is one of the most critical parts beceuase the won't pick up any errors inside
  • the structure must alwayus end with terminating NULL and 0 values. { NULL, NULL, 0, NULL }
  • Here we tell python the function has argumat, no argumarts or arguments and keywords

Example :

static PyMethodDef myMethods[] = {
  {"func1", func1, METH_NOARGS, "Func1 doc"},
  {"func2", func2, METH_NOARGS, "Func2 doc"},
  { NULL, NULL, 0, NULL }
}

Pattern used: pyMethodName, function, functionType, PyDocs

  • The PyModuleDef structure is wbhat we use to tell the PyModule_Create() function what information to use to create the module
  • We need to give it a name, documentation, tell python of we will control the modyle stat and the structure of methods to include in the module

Fibonnaci Example:

#include <Python.h>

int Cfib(int n){
  if (n < 2)
    return n;
  else
    return Cfib(n -1) + Cfib(n -2);
}

static PyObject* fib(PyObject* self, PyObject* args){
  int n;
  
  if(!PyArg_ParseTuple(args, "i", &n))
    return NULL;
    
  return Py_BuildValue("i", Cfib(n));
}

static PyObject* version(PyObject* self){
  return Py_BuildValue("s", "Version 1.0");
}

static PyMethodDef myMethods[] = {
    {"fib", fib, METH_VARARGS, "Calculate the fibonacci numbers."},
    {"version", (PyCFunction)version, METH_NOARGS, "Returns the version"},
    {NULL. NULL, 0, NULL}
};

static struct PyModuleDef myModule = {
  PyModuleDef_HEAD_INIT,
  "myModule",
  "Fibonacci Module",
  -1,
  myMethods
};

PyMODINIT_FUNC PyInit_myModule(void){
  return PyModule_Create(&myModule);
}