Home >Backend Development >C++ >How to Extract a Python Function\'s Return Value When Called from C/C ?

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

Linda Hamilton
Linda HamiltonOriginal
2024-12-25 01:23:141000browse

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 <Python.h>

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.

The above is the detailed content of How to Extract a Python Function\'s Return Value When Called from C/C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn