Writing a Python C Extension Module
Build a simple .so extension using the Python/C API.
C Extension Anatomy
A minimal C extension has: method functions, a method table, a module definition struct, and a PyInit_ entry point.
// myext.c skeleton
#include <Python.h>
static PyObject* say_hello(PyObject* self, PyObject* args) {
Py_RETURN_NONE;
}
static PyMethodDef methods[] = {
{"say_hello", say_hello, METH_NOARGS, "Print hello"},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef module = {
PyModuleDef_HEAD_INIT, "myext", NULL, -1, methods
};
PyMODINIT_FUNC PyInit_myext(void) {
return PyModule_Create(&module);
}Parsing Arguments
PyArg_ParseTuple(args, "ii", &a, &b) parses Python arguments into C variables. Format codes: i=int, d=double, s=char*, O=PyObject*.
static PyObject* add(PyObject* self, PyObject* args) {
int a, b;
if (!PyArg_ParseTuple(args, "ii", &a, &b))
return NULL;
return PyLong_FromLong(a + b);
}All lessons in this course
- Why C Extensions? Use Cases and Trade-offs
- ctypes: Calling C Libraries from Python
- cffi: C Foreign Function Interface
- Writing a Python C Extension Module