SlideShare a Scribd company logo
Interfacing C/C++ with
Python
Ovidiu Farauanu
Iasi C/C++ Developers Meetup
15.01.2025
Embedding Python in C/C++
Embedding Python in C/C++
- Python is an old language and conservative language, but still very popular (TIOBE language of the
year 2024, 2021, 2020, 2018, 
)
- Python can be easily embedded into C/C++ applications or other technologies that expose a C-based
FFI
- In principle it works more or less the same way as when Lua or JavaScript are embedded (except Lua is
not refcounted but stack based)
- We won’t use any C++ specific API, the Python API is a C level API; C++ wrappers can be created
- Valid only for the CPython implementation (pypy requires cpyext to use the CPython C API)
Embedding Python in C/C++
Fundamentals
- Python.h header is the include entry point and contains several other header files that define all the
interfaces used to interact with the Python code
- The PyObject structure is the cornerstone of the Python’s object system enabling Python’s dynamic
object model
- Official documentation: https://docs.python.org/3.8/c-api/index.html
Environment variables
PYTHONHOME - Change the location of the standard Python libraries.
PYTHONPATH - Augment the default search path for module files.
export PYTHONHOME=/c/msys64/mingw64
export PYTHONPATH="$SCRIPT_DIR:/c/msys64/mingw64/lib/python3.11"
Functions
Py_Initialize - Initialize the Python interpreter. In an application embedding Python, this should be called
before using any other Python/C API functions
Py_Finalize - Undo all initializations made by Py_Initialize() and subsequent use of Python/C API
functions, and destroy all sub-interpreters
Py_IsInitialized - Return true (nonzero) when the Python interpreter has been initialized, false (zero) if not.
After Py_FinalizeEx() is called, this returns false until Py_Initialize() is called again.
PyRun_SimpleString - Executes the Python source code from command in the __main__ module
PyImport_ImportModule - Import a module. This is best described by referring to the built-in Python function
__import__().
# simple.py
def plus(a, b):
return a + b
Embedding Python in C/C++
#include <Python.h>
int main(int argc, char const *argv[])
{
// Initialize python access
Py_Initialize();
// Import the simple.py code
PyObject* module = PyImport_ImportModule("simple");
Embedding Python in C/C++
Functions
PyObject_GetAttrString - Retrieve an attribute named attr_name from object o.
PyCallable_Check - Determine if the object o is callable. Return 1 if the object is callable and 0 otherwise. This
function always succeeds.
PyTuple_New - Return a new tuple object of size len, or NULL on failure.
PyTuple_SetItem - Insert a reference to object o at position pos of the tuple pointed to by p.
PyObject_CallObject - Call a callable Python object callable, with arguments given by the tuple args
PyLong_AsLong - Return a C long representation of obj.
Py_DECREF - Decrement the reference count for object o.
// Access the attribute named plus
PyObject* func = PyObject_GetAttrString(module, "plus");
// Make sure the attribute is callable
if (func && PyCallable_Check(func)) {
// Create a tuple to contain the function's args
PyObject* args = PyTuple_New(2);
PyTuple_SetItem(args, 0, PyLong_FromLong(4));
PyTuple_SetItem(args, 1, PyLong_FromLong(7));
// Execute the plus function in simple.py
PyObject* ret = PyObject_CallObject(func, args);
Py_DECREF(args);
Py_DECREF(func);
Py_DECREF(module);
Embedding Python in C/C++
// Convert the value to long and print
long retVal = PyLong_AsLong(ret);
std::cout << "Result: " << retVal << std::endl;
// prints ‘Result: 11’
Embedding Python in C/C++
g++ -I${PYTHON_INC} main.cpp -L/c/msys64/mingw64/lib -lpython3.11
# required to be able to load python modules from the current folder
SCRIPT_DIR=$(dirname "$(realpath "$0")")
EXT_DIR=$SCRIPT_DIR/build/lib.mingw_x86_64-cpython-311
export PYTHONHOME=/c/msys64/mingw64
export PYTHONPATH="$SCRIPT_DIR:$EXT_DIR:/c/msys64/mingw64/lib/python3.11"
Embedding Python in C/C++
Create a Python Extension
Functions
PyArg_ParseTuple - Parse the parameters of a function that takes only positional parameters into local
variables.
PyLong_FromLong - Return a new PyLongObject object from a C long long, or NULL on failure.
PyModule_Create - Create a new module object, given the definition in def.
// A simple function: adds two numbers
static PyObject* example_add(PyObject* self, PyObject* args) {
int a, b;
// Parse the input tuple
if (!PyArg_ParseTuple(args, "ii", &a, &b)) {
return NULL;
}
// Return the sum
return PyLong_FromLong(a + b);
}
Create a Python Extension
// Method definitions
static PyMethodDef ExampleMethods[] = {
{"add", example_add, METH_VARARGS, "Add two integers."},
{NULL, NULL, 0, NULL} // Sentinel
};
Create a Python Extension
// Module definition
static struct PyModuleDef examplemodule = {
PyModuleDef_HEAD_INIT,
"example", // Name of the module
NULL, // Module documentation (optional)
-1, // Size of per-interpreter state (-1 if no state)
ExampleMethods
};
Create a Python Extension
// Module initialization function
PyMODINIT_FUNC PyInit_example(void) {
return PyModule_Create(&examplemodule);
}
Create a Python Extension
Create a Python Extension
# setup.py
from setuptools import setup, Extension
module = Extension(
"example",
sources=["examplemodule.c"],
extra_compile_args=["-std=c99"], # GCC flag for C99 standard
extra_link_args=[],
)
setup(
name="example",
version="1.0",
description="A simple C extension for Python using GCC",
ext_modules=[module],
)
Create a Python Extension
# Build the extension
python setup.py build
# Calling C extension from python code
import example
res = example.add(10, 20)
print(res)
Questions?
Some extras: C++ wrappers
for the Python module. A good exercise
Some extras: C++ wrappers
The constructor
Some extras: C++ wrappers
Thanks!

More Related Content

Similar to Interfacing C++ with Python to boost your legacy apps with Python interfaces (20)

PPTX
C pythontalk
Nicholaus Jackson
 
PDF
Bind Python and C @ COSCUP 2015
Jian-Hong Pan
 
PDF
Cython - close to metal Python
Taras Lyapun
 
PDF
Brief Introduction to Cython
Aleksandar Jelenak
 
PDF
Threads and Callbacks for Embedded Python
Yi-Lung Tsai
 
PDF
Extending Python - FOSDEM 2015
fcofdezc
 
PDF
Start Wrap Episode 11: A New Rope
Yung-Yu Chen
 
PDF
Extending Python - Codemotion Milano 2014
fcofdezc
 
PDF
Extending Python, what is the best option for me?
Codemotion
 
PDF
Interfacing C/C++ and Python with SWIG
David Beazley (Dabeaz LLC)
 
PDF
Pybind11 - SciPy 2021
Henry Schreiner
 
PDF
Take advantage of C++ from Python
Yung-Yu Chen
 
PDF
Extending Python with ctypes
Anant Narayanan
 
PDF
Cython compiler
Tanikella Sai Abhijyan
 
PDF
OpenSAF Symposium_Python Bindings_9.21.11
OpenSAF Foundation
 
ODP
Pythonpresent
Chui-Wen Chiu
 
PDF
PyCon 2013 : Scripting to PyPi to GitHub and More
Matt Harrison
 
ODP
Programming Under Linux In Python
Marwan Osman
 
PPT
Introduction to cython
John(Qiang) Zhang
 
PDF
Harmonic Stack for Speed
Yung-Yu Chen
 
C pythontalk
Nicholaus Jackson
 
Bind Python and C @ COSCUP 2015
Jian-Hong Pan
 
Cython - close to metal Python
Taras Lyapun
 
Brief Introduction to Cython
Aleksandar Jelenak
 
Threads and Callbacks for Embedded Python
Yi-Lung Tsai
 
Extending Python - FOSDEM 2015
fcofdezc
 
Start Wrap Episode 11: A New Rope
Yung-Yu Chen
 
Extending Python - Codemotion Milano 2014
fcofdezc
 
Extending Python, what is the best option for me?
Codemotion
 
Interfacing C/C++ and Python with SWIG
David Beazley (Dabeaz LLC)
 
Pybind11 - SciPy 2021
Henry Schreiner
 
Take advantage of C++ from Python
Yung-Yu Chen
 
Extending Python with ctypes
Anant Narayanan
 
Cython compiler
Tanikella Sai Abhijyan
 
OpenSAF Symposium_Python Bindings_9.21.11
OpenSAF Foundation
 
Pythonpresent
Chui-Wen Chiu
 
PyCon 2013 : Scripting to PyPi to GitHub and More
Matt Harrison
 
Programming Under Linux In Python
Marwan Osman
 
Introduction to cython
John(Qiang) Zhang
 
Harmonic Stack for Speed
Yung-Yu Chen
 

More from Ovidiu Farauanu (13)

PDF
SIMD with C++ 26 by Alexandru Pentilescu
Ovidiu Farauanu
 
PDF
Introduction to C++20 Coroutines by Alex P
Ovidiu Farauanu
 
PDF
Back in Business with C++
Ovidiu Farauanu
 
PDF
Interface Oxidation
Ovidiu Farauanu
 
PDF
Optimization of the build times using Conan
Ovidiu Farauanu
 
PDF
Bind me if you can
Ovidiu Farauanu
 
PDF
Distributed Cache, bridging C++ to new technologies (Hazelcast)
Ovidiu Farauanu
 
PPTX
Monadic Computations in C++14
Ovidiu Farauanu
 
PDF
Domain Specific Languages and C++ Code Generation
Ovidiu Farauanu
 
PDF
Florentin Picioroaga - C++ by choice
Ovidiu Farauanu
 
PDF
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Ovidiu Farauanu
 
PDF
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)
Ovidiu Farauanu
 
PDF
Cap'n Proto (C++ Developer Meetup Iasi)
Ovidiu Farauanu
 
SIMD with C++ 26 by Alexandru Pentilescu
Ovidiu Farauanu
 
Introduction to C++20 Coroutines by Alex P
Ovidiu Farauanu
 
Back in Business with C++
Ovidiu Farauanu
 
Interface Oxidation
Ovidiu Farauanu
 
Optimization of the build times using Conan
Ovidiu Farauanu
 
Bind me if you can
Ovidiu Farauanu
 
Distributed Cache, bridging C++ to new technologies (Hazelcast)
Ovidiu Farauanu
 
Monadic Computations in C++14
Ovidiu Farauanu
 
Domain Specific Languages and C++ Code Generation
Ovidiu Farauanu
 
Florentin Picioroaga - C++ by choice
Ovidiu Farauanu
 
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Ovidiu Farauanu
 
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)
Ovidiu Farauanu
 
Cap'n Proto (C++ Developer Meetup Iasi)
Ovidiu Farauanu
 
Ad

Recently uploaded (20)

PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PDF
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PPTX
Fundamentals_of_Microservices_Architecture.pptx
MuhammadUzair504018
 
PDF
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PPTX
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
PPTX
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
Coefficient of Variance in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
PDF
Powering GIS with FME and VertiGIS - Peak of Data & AI 2025
Safe Software
 
PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
PPTX
Equipment Management Software BIS Safety UK.pptx
BIS Safety Software
 
PPTX
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
DOCX
Import Data Form Excel to Tally Services
Tally xperts
 
PDF
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
PPTX
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
PDF
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
PDF
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
PDF
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
Fundamentals_of_Microservices_Architecture.pptx
MuhammadUzair504018
 
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Coefficient of Variance in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
Powering GIS with FME and VertiGIS - Peak of Data & AI 2025
Safe Software
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
Equipment Management Software BIS Safety UK.pptx
BIS Safety Software
 
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
Import Data Form Excel to Tally Services
Tally xperts
 
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
Ad

Interfacing C++ with Python to boost your legacy apps with Python interfaces

  • 1. Interfacing C/C++ with Python Ovidiu Farauanu Iasi C/C++ Developers Meetup 15.01.2025
  • 3. Embedding Python in C/C++ - Python is an old language and conservative language, but still very popular (TIOBE language of the year 2024, 2021, 2020, 2018, 
) - Python can be easily embedded into C/C++ applications or other technologies that expose a C-based FFI - In principle it works more or less the same way as when Lua or JavaScript are embedded (except Lua is not refcounted but stack based) - We won’t use any C++ specific API, the Python API is a C level API; C++ wrappers can be created - Valid only for the CPython implementation (pypy requires cpyext to use the CPython C API)
  • 4. Embedding Python in C/C++ Fundamentals - Python.h header is the include entry point and contains several other header files that define all the interfaces used to interact with the Python code - The PyObject structure is the cornerstone of the Python’s object system enabling Python’s dynamic object model - Official documentation: https://docs.python.org/3.8/c-api/index.html
  • 5. Environment variables PYTHONHOME - Change the location of the standard Python libraries. PYTHONPATH - Augment the default search path for module files. export PYTHONHOME=/c/msys64/mingw64 export PYTHONPATH="$SCRIPT_DIR:/c/msys64/mingw64/lib/python3.11"
  • 6. Functions Py_Initialize - Initialize the Python interpreter. In an application embedding Python, this should be called before using any other Python/C API functions Py_Finalize - Undo all initializations made by Py_Initialize() and subsequent use of Python/C API functions, and destroy all sub-interpreters Py_IsInitialized - Return true (nonzero) when the Python interpreter has been initialized, false (zero) if not. After Py_FinalizeEx() is called, this returns false until Py_Initialize() is called again. PyRun_SimpleString - Executes the Python source code from command in the __main__ module PyImport_ImportModule - Import a module. This is best described by referring to the built-in Python function __import__().
  • 7. # simple.py def plus(a, b): return a + b Embedding Python in C/C++
  • 8. #include <Python.h> int main(int argc, char const *argv[]) { // Initialize python access Py_Initialize(); // Import the simple.py code PyObject* module = PyImport_ImportModule("simple"); Embedding Python in C/C++
  • 9. Functions PyObject_GetAttrString - Retrieve an attribute named attr_name from object o. PyCallable_Check - Determine if the object o is callable. Return 1 if the object is callable and 0 otherwise. This function always succeeds. PyTuple_New - Return a new tuple object of size len, or NULL on failure. PyTuple_SetItem - Insert a reference to object o at position pos of the tuple pointed to by p. PyObject_CallObject - Call a callable Python object callable, with arguments given by the tuple args PyLong_AsLong - Return a C long representation of obj. Py_DECREF - Decrement the reference count for object o.
  • 10. // Access the attribute named plus PyObject* func = PyObject_GetAttrString(module, "plus"); // Make sure the attribute is callable if (func && PyCallable_Check(func)) { // Create a tuple to contain the function's args PyObject* args = PyTuple_New(2); PyTuple_SetItem(args, 0, PyLong_FromLong(4)); PyTuple_SetItem(args, 1, PyLong_FromLong(7)); // Execute the plus function in simple.py PyObject* ret = PyObject_CallObject(func, args); Py_DECREF(args); Py_DECREF(func); Py_DECREF(module); Embedding Python in C/C++
  • 11. // Convert the value to long and print long retVal = PyLong_AsLong(ret); std::cout << "Result: " << retVal << std::endl; // prints ‘Result: 11’ Embedding Python in C/C++
  • 12. g++ -I${PYTHON_INC} main.cpp -L/c/msys64/mingw64/lib -lpython3.11 # required to be able to load python modules from the current folder SCRIPT_DIR=$(dirname "$(realpath "$0")") EXT_DIR=$SCRIPT_DIR/build/lib.mingw_x86_64-cpython-311 export PYTHONHOME=/c/msys64/mingw64 export PYTHONPATH="$SCRIPT_DIR:$EXT_DIR:/c/msys64/mingw64/lib/python3.11" Embedding Python in C/C++
  • 13. Create a Python Extension
  • 14. Functions PyArg_ParseTuple - Parse the parameters of a function that takes only positional parameters into local variables. PyLong_FromLong - Return a new PyLongObject object from a C long long, or NULL on failure. PyModule_Create - Create a new module object, given the definition in def.
  • 15. // A simple function: adds two numbers static PyObject* example_add(PyObject* self, PyObject* args) { int a, b; // Parse the input tuple if (!PyArg_ParseTuple(args, "ii", &a, &b)) { return NULL; } // Return the sum return PyLong_FromLong(a + b); } Create a Python Extension
  • 16. // Method definitions static PyMethodDef ExampleMethods[] = { {"add", example_add, METH_VARARGS, "Add two integers."}, {NULL, NULL, 0, NULL} // Sentinel }; Create a Python Extension
  • 17. // Module definition static struct PyModuleDef examplemodule = { PyModuleDef_HEAD_INIT, "example", // Name of the module NULL, // Module documentation (optional) -1, // Size of per-interpreter state (-1 if no state) ExampleMethods }; Create a Python Extension
  • 18. // Module initialization function PyMODINIT_FUNC PyInit_example(void) { return PyModule_Create(&examplemodule); } Create a Python Extension
  • 19. Create a Python Extension # setup.py from setuptools import setup, Extension module = Extension( "example", sources=["examplemodule.c"], extra_compile_args=["-std=c99"], # GCC flag for C99 standard extra_link_args=[], ) setup( name="example", version="1.0", description="A simple C extension for Python using GCC", ext_modules=[module], )
  • 20. Create a Python Extension # Build the extension python setup.py build # Calling C extension from python code import example res = example.add(10, 20) print(res)
  • 22. Some extras: C++ wrappers for the Python module. A good exercise
  • 23. Some extras: C++ wrappers The constructor
  • 24. Some extras: C++ wrappers