"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Call Python function from C/C++ and get the return value method

Call Python function from C/C++ and get the return value method

Posted on 2025-04-18
Browse:424

How to Extract a Python Function\'s Return Value When Called from C/C  ?

Extracting Return Value from a Python Function Called in C/C

Calling a custom Python function from C/C allows for extended functionality, but extracting the return value can be challenging. Here's a solution using the Python C-API.

The Python Module

Create a Python module (mytest.py):

import math

def myabs(x):
    return math.fabs(x)

The C/C Code

Import the python3 interpreter in C/C (test.cpp):

#include 

int main() {
    Py_Initialize();
    PyRun_SimpleString("import sys; sys.path.append('.')");

Importing and Calling the Function

  1. Import the Python module:
PyObject* myModuleString = PyString_FromString("mytest");
PyObject* myModule = PyImport_Import(myModuleString);
  1. Get a reference to the function:
PyObject* myFunction = PyObject_GetAttrString(myModule, "myabs");
  1. Construct the function arguments:
PyObject* args = PyTuple_Pack(1, PyFloat_FromDouble(2.0));
  1. Call the function:
PyObject* myResult = PyObject_CallObject(myFunction, args);

Extracting the Return Value

Convert the result to a double:

double result = PyFloat_AsDouble(myResult);

Usage

In your C/C code, you can now use the extracted return value (result):

printf("Absolute value: %f\n", result);

Note: Remember to check for any errors during these operations. For more details on the C-API, refer to the official documentation.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3