Well, the memory address of a compiled function is obtained but how to turn it to Python callable that can be used as an extension. The answer to this the use of ctypes module that can create a Python callable and can wrap arbitrary memory address.
The code below shows how to obtain the raw, low-level address of a C function and how to turn it back into a callable object.
addr : 140735505915760
Code #2 : Turn the address into a callable function
Function : <CFunctionType object at 0x1006816d0>
Code #3 : Call the resulting function
func(2) : 0.9092974268256817 func(0) : 0.0
A CFUNCTYPE instance has to be created first to make a callable. The first argument to
CFUNCTYPE() is the return type. Next arguments are the types of arguments. After defining the function type, it is wrapped around an integer memory address to create a callable object. The resulting object is used like any normal function accessed through ctypes.
It is becoming increasingly common for programs and libraries to utilize advanced code generation techniques like just-in-time compilation, as found in libraries such as LLVM (LLVM itself is not an acronym; it is the full name of the project.)
The code below uses the llvmpy extension to make an assembly function, obtain a function pointer to it, and turn it into a Python callable.
Code #4 :
<llvm.core.Instruction object at 0x10078e990>
Code #5 :
Code #6 : Call the resulting function
13.0 41.0 5.0
- callable() in Python
- Python | How to get function name ?
- Help function in Python
- Python | int() function
- Python | oct() function
- Python | dir() function
- Python | now() function
- Python | hex() function
- id() function in Python
- sum() function in Python
- ord() function in Python
- Python | cmp() function
- Python map() function
- Numpy Meshgrid function
- Python | math.tan() function
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.