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
Release: 2024-12-25 01:23:14
Original
930 people have browsed it

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)
Copy after login

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('.')");
Copy after login

Importing and Calling the Function

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

Extracting the Return Value

Convert the result to a double:

double result = PyFloat_AsDouble(myResult);
Copy after login

Usage

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

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template