Skip to main content

44. C Extensions Basics

Python can be extended with C for performance-critical code.


Why Write C Extensions?

  • Speed up CPU-bound operations
  • Interface with existing C libraries

Minimal Example

// mymodule.c
#include <Python.h>

static PyObject* add(PyObject* self, PyObject* args) {
int a, b;
if (!PyArg_ParseTuple(args, "ii", &a, &b)) return NULL;
return PyLong_FromLong(a + b);
}

static PyMethodDef methods[] = {
{"add", add, METH_VARARGS, "Add two numbers"},
{NULL, NULL, 0, NULL}
};

static struct PyModuleDef module = {
PyModuleDef_HEAD_INIT, "mymodule", NULL, -1, methods
};

PyMODINIT_FUNC PyInit_mymodule(void) {
return PyModule_Create(&module);
}

Compile with setuptools or distutils.


Wrap-Up

C extensions boost performance and connect Python with C libraries.