Call Python Class Method From C++

Call Python Class Method From C++

Integrating Python functionality into C++ applications can be advantageous when leveraging Python's extensive libraries and rapid development capabilities within existing C++ projects. However, bridging the gap between these two languages often poses challenges. This tutorial explains how to call Python class method from C++.

Let's say we have a simple Python script ( which defines a class with a method:

class Calculator:
    def sum(self, a, b):
        return a + b

We created the C++ program that calls the sum method of the Calculator class. The code retrieves the path of the current script and appends it to Python's sys.path, enabling the importation of the module. The code proceeds to import a Python module named test and retrieves the class Calculator from it. It creates an instance of the Calculator class, obtains the method named sum from the instance, and finally calls this method with arguments 2.0 and 5.0. The result is printed to the console.


#include <Python.h>
#include <filesystem>
#include <iostream>

int main(int argc, char *argv[])
    std::filesystem::path script(argv[0]);

    PyObject * sysPath = PySys_GetObject("path");
    PyList_Insert(sysPath, 0, PyUnicode_FromString(script.parent_path().c_str()));

    PyObject * pModule = PyImport_ImportModule("test");
    PyObject * pClass = PyObject_GetAttrString(pModule, "Calculator");
    PyObject * pObj = PyObject_CallObject(pClass, nullptr);
    PyObject * pMethod = PyObject_GetAttrString(pObj, "sum");

    double result = PyFloat_AsDouble(PyObject_CallFunction(pMethod, "ff", 2.0, 5.0));
    std::cout << result << std::endl;


    return 0;

Leave a Comment

Cancel reply

Your email address will not be published.