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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With