How do I create a Python extension module in C?

Creating a Python extension module in C allows you to write performance-critical code and extend Python's capabilities. Below is a step-by-step guide to creating a simple Python extension module:

Step-by-Step Guide

  1. Write your C code in a file, for example, mymodule.c.
  2. Include the Python header files and implement your functions.
  3. Define methods and create a module structure.
  4. Compile the code into a shared library.
  5. Use the module in your Python code.

Example C Code

#include // Function to add two numbers static PyObject* my_add(PyObject* self, PyObject* args) { int a, b; if (!PyArg_ParseTuple(args, "ii", &a, &b)) { return NULL; } return Py_BuildValue("i", a + b); } // Method definitions static PyMethodDef MyMethods[] = { {"add", my_add, METH_VARARGS, "Add two integers"}, {NULL, NULL, 0, NULL} }; // Module definition static struct PyModuleDef mymodule = { PyModuleDef_HEAD_INIT, "mymodule", // name of module NULL, // module documentation, may be NULL -1, // size of per-interpreter state of the module, // or -1 if the module keeps state in global variables. MyMethods }; PyMODINIT_FUNC PyInit_mymodule(void) { return PyModule_Create(&mymodule); }

Compiling the Module

To compile the module, use the following command:

gcc -shared -o mymodule.so -fPIC $(python3 -m pybind11 --includes) mymodule.c

Using the Module in Python

Finally, you can use your compiled module in Python:

import mymodule print(mymodule.add(1, 2)) # Output: 3

Python extension C language Python module performance programming