Search code examples
pythonpython-c-api

How to call a python function by name from the C-API?


From the c-api, I would like to call a python function by name. I would then be calling the function with a list of python objects as arguments.

It is not clear to me in the Python documentation how I would get a "Callable" object from the main python interpreter.

Any help appreciated in:

  1. Getting the address from the function
  2. Calling the function with my PythonObject's as arguments.

I'm using Python 2.x series for my development.


Solution

  • Basically, you use the Python C API to get the module the function is contained in, then query the module dictionary for the function. That's more or less the same what the Python runtime does internally when your Python code invokes a function from somewhere.

    Relevant functions from the API to look at are PyImport_ImportModule, PyModule_GetDict, PyDict_GetItem and the PyObject_CallXXX family of functions.