Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why python can import a shared library as a module?

Tags:

python

swig

I have been learning to extend python by swig. In the swig tutor,it writes:

Building a Python module

Turning C code into a Python module is also easy. Simply do the following (shown for    Irix, see the SWIG Wiki Shared Libraries page for help with other operating systems):

unix % swig -python example.i
unix % gcc -c example.c example_wrap.c \
    -I/usr/local/include/python2.1
unix % ld -shared example.o example_wrap.o -o _example.so 

We can now use the Python module as follows :
 >>> import example
 >>> example.fact(5)
 120
 >>> example.my_mod(7,3)
 1
 >>> example.get_time()
 'Sun Feb 11 23:01:07 1996'
 >>>

It means that a shared library can be imported as a python module.But I know that a shared library file is a object file which consists of many machine code and some extra information, while a regular python module is ascii file or byte code file, how can the machine code be executed by python virtual machine, I am confused.

like image 746
Jack Chin Avatar asked Apr 06 '26 20:04

Jack Chin


1 Answers

In the end, all programs execute machine code. When Python loads a shared library, it calls a function initlibraryName; this function calls back into Python to tell it what types, functions and modules it has, and what the machine addresses of the functions and the type descriptors are. Python adds them to its table (noting that they are in a C module, and not Python code), and when you call them, it looks them up, notes that they are in an external module, and calls them accordingly.

like image 193
James Kanze Avatar answered Apr 09 '26 10:04

James Kanze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!