Including C or C++ code in Python can be very useful for performance-critical tasks or to use existing C/C++ libraries. There are several ways to do this, depending on your needs and the complexity of the integration. Here are the most common methods:
1. Using ctypes (C only)
Best for: Simple C functions, no C++ support.
How: Compile your C code as a shared library (.so on Linux, .dll on Windows, .dylib on macOS), then load and call functions using Python's ctypes module.
Example:
C code (myfuncs.c):
c
// myfuncs.c
int add(int a, int b) {
return a + b;
}
from setuptools import setup, Extension
setup(
ext_modules=[Extension("my_module", ["my_module.c"])]
)
Build:
sh
python setup.py build
python setup.py install
Python code:
python
import my_module
print(my_module.add(2, 3))
4. Using pybind11 (C++ only)
Best for: Modern C++ code, easy and powerful.
How: Use the pybind11 library to expose C++ classes and functions to Python.
Example:
C++ code (example.cpp):
cpp
#include <pybind11/pybind11.h>
namespace py = pybind11;
int add(int a, int b) {
return a + b;
}
PYBIND11_MODULE(example, m) {
m.def("add", &add, "A function that adds two numbers");
}