10

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.

user3415910
  • 440
  • 3
  • 5
  • 19
  • 1
    Is 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 Answers3

17

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))
Alan
  • 2,914
  • 2
  • 14
  • 26
4

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))
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.

Brad
  • 121
  • 1
  • 8