I have a c program(.c file). I am converting that to a shared object(.so). How can i call and run the shared object from my python code? If possible, please suggest me a list of libraries that can help me to do this task.
If you want to call functions inside a shared object, the the standard module ctypes is what you are after. No need for any external libraries.
Load a library:
from ctypes import *
# either
libc = cdll.LoadLibrary("libc.so.6")
# or
libc = CDLL("libc.so.6")
Then call a function from the library, the same as calling a Python function:
print(libc.time(None))
Caution to those using the recommended method. It doesnt work on windows and is for linux the code for the windows function is as follows :
from ctypes import *
libc = cdll.msvcrt
and to call it,
print(libc.time(None))
If the .so file exposes a PyInit_<module_name>
function, its path (or parent directory's path) can be added to the environment variable PYTHONPATH
. Then you can import the module via import <module_name>
. Note: it looks like the name of the .so file must match the module name <module_name>
that's exposed.
More information here: https://docs.python.org/3/extending/building.html
Adding this answer for reference.
© 2022 - 2024 — McMap. All rights reserved.