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):
#includeint 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.
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