Prerequisite: Calling Python from C | Set 1
A reference to an existing Python callable needs to be passed in, to use this function. To do that there are many ways like – simply writing C code to extract a symbol from an existing module or having a callable object passed into an extension module.
Code #1 : Simple embedding example
To build this last example, C needs to be compiled and link against the Python interpreter. The snippet below shows how to do it (this is something that might require some amount of fiddling with on your machine):
Code #2 :
Compiling and running the resulting executable gives output as :
0.00 0.00 0.10 0.01 0.20 0.04 0.30 0.09 0.40 0.16 ...
There is another example given by the code below that shows an extension function that receives a callable and some arguments and passes them to
call_func() for the purposes of testing.
Code #3 :
Code #4 : Testing the extension function
It is critical that first we need to have a Python object representing the callable that is to be invoked. This could be a function, class, method, built-in method, or anything that implements the
__call__() operation. To verify whether it is a callable function use
Code #5 : Checking
PyObject_Call() to call a function, supplying it with the callable object, a tuple of arguments, and an optional dictionary of keyword arguments.
Py_BuildValue() can be used to build the argument tuple or dictionary.
Code #6 :
- Calling Python from C | Set 1
- Python | Index of Non-Zero elements in Python list
- Reading Python File-Like Objects from C | Python
- Python | Convert list to Python array
- Important differences between Python 2.x and Python 3.x with examples
- Python | Merge Python key values to list
- Python | Set 4 (Dictionary, Keywords in Python)
- Python | Add Logging to a Python Script
- Python | Add Logging to Python Libraries
- Python | Sort Python Dictionaries by Key or Value
- Python | Visualizing O(n) using Python
- try and except in Python
- gcd() in Python
- Python Set | pop()
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.