Creating Python Modules with C and C++
1. Introduction
This guide explains how to write and build Python modules using C and C++. It covers: - C extensions for
Python - C++ extensions using pybind11 - Compiling and testing the modules
2. Prerequisites
• Python 3 installed
• build-essential (gcc, g++)
• pip
• For C++: pybind11 (optional but recommended)
Install essentials on Debian/Ubuntu:
sudo apt update
sudo apt install build-essential python3-dev python3-pip
pip3 install pybind11
3. Writing a C Extension Module
3.1 Simple C Module
Create example.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 ExampleMethods[] = {
{"add", add, METH_VARARGS, "Add two integers"},
{NULL, NULL, 0, NULL}
};
1
static struct PyModuleDef examplemodule = {
PyModuleDef_HEAD_INIT,
"example",
"Example C module",
-1,
ExampleMethods
};
PyMODINIT_FUNC PyInit_example(void) {
return PyModule_Create(&examplemodule);
}
3.2 Setup Script
Create [Link] :
from setuptools import setup, Extension
module = Extension('example', sources=['example.c'])
setup(
name='ExampleModule',
version='1.0',
description='Example Python C module',
ext_modules=[module]
)
3.3 Build & Install
python3 [Link] build
python3 [Link] install --user
3.4 Test
import example
print([Link](3, 4)) # Output: 7
2
4. Writing a C++ Extension Module (with pybind11)
4.1 Simple C++ Module
Create example_cpp.cpp :
#include <pybind11/pybind11.h>
int add(int i, int j) {
return i + j;
}
PYBIND11_MODULE(example_cpp, m) {
[Link]() = "Example C++ module using pybind11";
[Link]("add", &add, "Add two integers");
}
4.2 Setup Script
Create setup_cpp.py :
from setuptools import setup, Extension
import pybind11
ext_modules = [
Extension(
'example_cpp',
['example_cpp.cpp'],
include_dirs=[pybind11.get_include()],
language='c++'
)
]
setup(
name='ExampleCppModule',
version='1.0',
ext_modules=ext_modules
)
3
4.3 Build & Install
python3 setup_cpp.py build
python3 setup_cpp.py install --user
4.4 Test
import example_cpp
print(example_cpp.add(5, 6)) # Output: 11
5. Tips and Best Practices
• Always include Python.h first in C extensions.
• For C++, use extern "C" only if not using pybind11.
• Use python3-dev package for headers.
• Keep functions small and simple.
• Use setuptools instead of distutils .
• For larger projects, consider CMake + pybind11 integration.
6. References
• Python C API
• pybind11 Documentation
• Setuptools Documentation