gpt4 book ai didi

python - 为什么python可以将共享库作为模块导入?

转载 作者:太空宇宙 更新时间:2023-11-03 15:19:18 25 4
gpt4 key购买 nike

我一直在学习通过 swig 来扩展 python。在痛饮导师中,它写道:

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'
>>>

这意味着共享库可以作为 python 模块导入。但我知道共享库文件是一个目标文件,它由许多机器代码和一些额外信息组成,而常规 python 模块是 ascii 文件或字节代码文件,机器码怎么能被python虚拟机执行,我很困惑。

最佳答案

最后,所有程序都执行机器码。当 Python加载一个共享库,它调用一个函数 init<i>libraryName</i> ;这个函数回调进入 Python 以告诉它它有哪些类型、函数和模块,以及机器地址的功能和类型描述符是。 Python 将它们添加到它的表中(注意它们在 C 模块中,而不是 Python 代码中),当你调用他们,它查找他们,注意到他们在外部模块,并相应地调用它们。

关于python - 为什么python可以将共享库作为模块导入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17678515/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com