In this article, we will mainly focus on safe execution of a Python callable from C, returning a result back to C and writing C code that needs to access a Python function as a callback.
The code below focuses on the tricky parts that are involved in calling Python from C.
Code #1 : [Step 1 and 2] Own the GIL and Verify that function is a proper callable
Code #2 : Building Arguments, calling function, Check for Python exceptions
Create the return value, Restore previous GIL state and return.
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.
The code given below shows calling a function from an embedded Python interpreter.
Code #3 : Loading a symbol from a module
- Calling Python from C | Set 2
- Reading Python File-Like Objects from C | Python
- Python | Merge Python key values to list
- Python | Convert list to Python array
- Python | Index of Non-Zero elements in Python list
- Important differences between Python 2.x and Python 3.x with examples
- Python | Set 4 (Dictionary, Keywords in Python)
- Python | Sort Python Dictionaries by Key or Value
- Python | Add Logging to a Python Script
- Python | Add Logging to Python Libraries
- Python | Visualizing O(n) using Python
- bin() in Python
- Python vs PHP
- Use of min() and max() in Python
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.