Call Python Function that Returns List From C++

Call Python Function that Returns List From C++

Integrating C++ with Python offers a powerful combination, allowing you to leverage the performance of C++ and the flexibility of Python. Integration between these two languages frequently presents challenges. This tutorial explains how to call a Python function that returns a list from C++.

Let's say we have a simple Python script named test.py that defines a function returning a list:

test.py

def get_list():
    return [1, 2, 3]

We created the C++ program that calls the get_list function. The code gets the current script's path and includes it in Python's sys.path, allowing the module to be imported. Then the code imports a Python module named test and calls a function which returns a list. The retrieved list is converted into a C++ vector, and its elements are printed to the console.

main.cpp

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

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

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

    PyObject *pModule = PyImport_ImportModule("test");
    PyObject *pFunc = PyObject_GetAttrString(pModule, "get_list");

    PyObject *list = PyObject_CallNoArgs(pFunc);
    Py_ssize_t size = PyList_Size(list);

    std::vector<int> data;
    data.reserve(size);
    for (int i = 0; i < size; ++i) {
        data.emplace_back(PyLong_AsLong(PyList_GetItem(list, i)));
    }

    for (int i = 0; i < size; ++i) {
        std::cout << data[i] << std::endl;
    }

    Py_Finalize();

    return 0;
}

Leave a Comment

Cancel reply

Your email address will not be published.