How to run .so files using through python script
Asked Answered
O

3

12

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.

Overbite answered 22/2, 2018 at 4:36 Comment(3)
Is the C library meant to be called from Python?Taw
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.Overbite
SWIG is very easy to use: swig.org/Doc3.0/Python.html#Python_nn3Skier
D
19

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))
Decosta answered 22/2, 2018 at 5:0 Comment(1)
It is ok but not so elagant. The best solution should allow user to directly import it.Amagasaki
B
3

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))
Bennettbenni answered 20/9, 2019 at 2:30 Comment(1)
You too are totally off-topic. Read the question again. It speaks about .so files.Neuropathy
W
0

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.

Waggon answered 31/5, 2022 at 19:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.