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
PyObject* myModuleString = PyString_FromString("mytest"); PyObject* myModule = PyImport_Import(myModuleString);
PyObject* myFunction = PyObject_GetAttrString(myModule, "myabs");
PyObject* args = PyTuple_Pack(1, PyFloat_FromDouble(2.0));
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!