0

Say I have a function

def pyfunc():
    print("ayy lmao")
    return 4

and I want to call it in c++

int j = (int)python.pyfunc();

how exactly would I do that?

2 Answers2

0

You might want to have a look into this:https://docs.python.org/2/extending/extending.html

Amjad Syed
  • 185
  • 1
  • 1
  • 8
0

In order to call a Python function from C++, you have to embed Python in your C++ application. To do this, you have to:

  1. Load the Python DLL. How you do this is system dependent: LoadLibrary under Windows, dlopen under Unix. If the Python DLL is in the usual path you use for DLLs (%path% under Windows, LD_LIBRARY_PATH under Unix), this will happen automatically if you try calling any function in the Python C interface. Manual loading will give you more control with regards to version, etc.

  2. Once the library has been loaded, you have to call the function Py_Initialize() to initialize it. You may want to call Py_SetProgramName() or Py_SetPythonHome() first to establish the environment.

  3. Your function is in a module, so you'll have to load that: PyImport_ImportModule. If the module isn't in the standard path, you'll have to add its location to sys.path: use PyImport_ImportModule to get the module "sys", then PyObject_GetAttrString to get the attribute "path". The path attribute is a list, so you can use any of the list functions to add whatever is needed to it.

  4. Your function is an attribute of the module, so you use PyObject_GetAttrString on the module to get an instance of the function. Once you've got that, you pack the arguments into a tuple or a dictionary (for keyword arguments), and use PyObject_Call to call it.

All of the functions, and everything that is necessary, is documented (extremely well, in fact) in https://docs.python.org/2/c-api/. You'll be particularly interested in the sections on "Embedding Python" and "Importing Modules", along with the more general utilities ("Object Protocol", etc.). You'll also need to understand the general principles with regards to how the Python/C API works—things like reference counting and borrowed vs. owned references; you'll probably want to read all of the sections in the Introduction first.

And of course, despite the overall quality of the documentation, it's not perfect. A couple of times, I've had to plunge into the Python sources to figure out what was going on. (Typically, when I'm getting an error back from Python, to find out what it's actually complaining about.)

James Kanze
  • 150,581
  • 18
  • 184
  • 329