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.
-
1Is the C library meant to be called from Python?– Davis HerringFeb 22, 2018 at 4:39
-
I just wanted to execute the file, some thing like calling a python function with out parameters and storing the result in a python variable for further execution in python. Hope you can understand my problem.– user3415910Feb 22, 2018 at 4:45
-
SWIG is very easy to use: swig.org/Doc3.0/Python.html#Python_nn3– cwhelmsFeb 22, 2018 at 5:13
3 Answers
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))
-
You too are totally off-topic. Read the question again. It speaks about .so files. May 19 at 10:27
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.