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 Herring Feb 22 '18 at 04: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. – user3415910 Feb 22 '18 at 04:45
-
SWIG is very easy to use: http://www.swig.org/Doc3.0/Python.html#Python_nn3 – cwhelms Feb 22 '18 at 05: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))

- 2,914
- 2
- 14
- 26
-
It is ok but not so elagant. The best solution should allow user to directly import it. – runzhi xiao Nov 17 '22 at 06:40
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))

- 49
- 1
- 1
-
1You too are totally off-topic. Read the question again. It speaks about .so files. – Apostolos May 19 '22 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.

- 121
- 1
- 8