Featured image of post Calling C++ Dynamic Libraries in Python

Calling C++ Dynamic Libraries in Python

ctypes or pybind11?

  • When working on a Python project recently, I needed to call C++ dynamic library files. Both Python’s built-in ctypes library and the pybind11 library can interface with dynamic libraries.

ctypes

pybind11

  • pybind11 is a library that compiles C++ code into Python-compatible dynamic libraries: https://github.com/pybind/pybind11
  • Have C++ colleagues build the .so file and share just that file
  • Key considerations:
    • Ensure build environment Python version matches runtime environment
    • Generated filename format: xxxx.cpython-311(version)-x86_64(architecture)-linux-gnu(OS).so
    • Place the file in project directory, e.g., app/libs/xxx/xxxx.so
    • Execute export PYTHONPATH="$PYTHONPATH:/var/www/app/libs/xxx" (prevents ModuleNotFoundError: No module named xxx)

Type Hinting

  • Install stub generator: pip install pybind11-stubgen
  • Generate stubs in the .so directory: pybind11-stubgen xxx -o .
  • Import and use the generated stubs for type hinting in other modules