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
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course