Calling a python method from C/C++, and extracting its return value -


I would like to call a custom function that is defined by C in python module. I have some initial code that, but it just prints the output at stdout.

mytest.py

  Import Mathematics Def Mybas (x): return matheable.fabs (X)  

test.cpp

  #include & lt; Python H & gt; Int main () {Py_Initialize (); PyRun_SimpleString ("Import System; sys.path.append ('.')"); PyRun_SimpleString ("Import mytest;"); PyRun_SimpleString ("print mytest.myabs (2.0)"); Py_Finalize (); Return 0; }  

How can I remove the return value in C and use it in C?

You must use the methods provided by C-API (Certainly).

First of all, you will need to learn about PyObject which is the original object for the C API. This can represent any type of dragon basic type (string, float, int, ...).

For example, many functions exist to change the dragon string * or repeat the peephlots.

First of all, import your module:

  PyObject * myModuleString = PyString_FromString ((four *) "mytest"); PyObject * myModule = PyImport_Import (myModuleString);  

Then get a reference to your function:

  PyObject * myFunction = PyObject_GetAttrString (myModule, (four *) "myabs"); PyObject * args = PyTuple_Pack (1, PyFloat_FromDouble (2.0));  

Then your result is getting:

  PyObject * myResult = PyObject_CallObject (myFunction, args)  

And getting back to a double:

  double results = PyFloat_AsDouble (myResult);  

You should obviously check the errors (the CF link given by Mark Tollonan).

If you have any questions, do not hesitate. Best wishes


Comments