Using a python function in C++

My question concerns using a pre-defined python function in a C++ script. I have looked at the documentation for this, and yet it is not very understandable to a first user.

Suppose I have a python function of the following form:

def example(a):
y=a**2
return y

Now I want to call this python function into a C++ script so that I can use it. Schematically, I want something like this:

int main()
{ int t=6
int r
r=example(t)
return r
}

Can someone please explain in detail and simply what I need to do for this to work?
i read through this link and I am still confused. Might you be willing to unfold the complexity for me?
What you are trying to do isn't particularly difficult, but it is a lot more involved than you might think.

If I understand what you want, you only need the "Very High Level Embedding" part.

Put your python functions in a file and source it with PyRun_SimpleFile().
You can then use the functions with PyRun_String().
That will return you a pointer to a PyObject, which you can examine for the python function's result.
Don't forget to properly dispose of the PyObject when you are done with it with Py_XDECREF().

More docs.
https://docs.python.org/3/c-api/veryhigh.html
https://docs.python.org/3/c-api/structures.html

The hardest part will be compiling and linking.

Good luck!
Topic archived. No new replies allowed.