Build C++ Program that Calls Python Function using CMake

Build C++ Program that Calls Python Function using CMake

In today's software development landscape, the integration of multiple programming languages has become a common requirement. This integration allows developers to leverage the strengths of different languages within a single project. One powerful combination is the integration of C++ and Python, where C++ provides high performance and Python offers ease of scripting and rapid development. This tutorial shows how to build the C++ program that calls a Python function using CMake.

Prepare environment

Ensure that you have Python 3 development package, CMake, and a C++ compiler (such as g++ or Visual C++) installed on your system before proceeding.

Build C++ program

  • Step 1: Create a new C++ project

Create a new directory for C++ project. For instance, create a directory named test_cpp_python for a basic project that invokes a Python function to calculate the sum of two numbers. Once the directory is set up, move into it.

mkdir test_cpp_python && cd test_cpp_python
  • Step 2: Create CMakeLists.txt file

Within the project directory, create a CMakeLists.txt file. This file will house the directives for CMake to configure and produce the necessary build scripts.

test_cpp_python/CMakeLists.txt

cmake_minimum_required(VERSION 3.27)
project(myapp)

set(CMAKE_CXX_STANDARD 17)

find_package(Python3 COMPONENTS Development REQUIRED)

add_executable(${PROJECT_NAME} main.cpp)

target_link_libraries(${PROJECT_NAME} Python3::Python)

The find_package command searches for the Python3 package, specifically looking for components needed for development. It is marked as REQUIRED, meaning that if CMake cannot find the necessary components, it will result in an error.

The add_executable command defines the source files that need to be compiled to generate an executable.

The target_link_libraries command specifies that the executable should be linked with the Python3 library. The Python3::Python part is a CMake target that encapsulates the necessary information for linking with the Python library.

  • Step 3: Create source file

Within the project directory, create a source file named main.cpp.

test_cpp_python/main.cpp

#include <Python.h>
#include <filesystem>
#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, "sum");

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

    Py_Finalize();

    return 0;
}

This C++ code snippet demonstrates a program that embeds and calls a Python function. It begins by including necessary headers and initializing Python with Py_Initialize. The script's path is obtained and added to Python's sys.path, enabling module importation. The code then imports a Python module named test (test.py script) and retrieves a function named sum from it. Finally, it invokes the Python function with arguments (2.0, 5.0) and prints the result. The Python interpreter is appropriately finalized with Py_Finalize before the program concludes.

  • Step 4: Configure the project with CMake

Within the project directory, execute the following CMake command to generate the build scripts and configure the project.

cmake -S . -B build

The -S option specifies the source directory, which, in this case, is set to the current directory. The -B option indicates the build directory, named build in this example.

  • Step 5: Build the project with CMake

Run the following CMake command to build a project.

cmake --build build

The usage of the --build option informs CMake to execute a build operation within the designated directory.

  • Step 6: Create Python script

Inside the build directory, create a Python script named test.py for calculating the sum of two numbers.

build/test.py

def sum(a, b):
    return a + b
  • Step 6: Run the program

You can run the program as follows:

./build/myapp

Output:

7

Leave a Comment

Cancel reply

Your email address will not be published.