如果使用过 Visual Studio 的话,应该对项目配置中的选择运行时库类型有印象,根据不同的选项,对应链接底层不同名字的运行时库。
Python 根据版本、编译选项的不同而有不同的 ABI,因此对于同一个扩展库,必须针对不同的 Python ABI 构建不同的版本,因此也有不同的命名,Python2 的扩展库的名字非常简单(这套命名规则是 Python3.2 提出来的),如:x.so
,但 Python3 的扩展库使用了类似 VC 运行时库的命名规则,如:x.cpython-36d-x86_64-linux-gnu.so
。
可以通过如下命令查看不同 Python 版本的 ABI:
1 2 3 4 5 6 7 8
| $ /usr/bin/python2 Python 2.7.15+ (default, Nov 27 2018, 23:36:35) [GCC 7.3.0] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sysconfig >>> sysconfig.get_config_var('SOABI') >>> sysconfig.get_config_var('EXT_SUFFIX') >>>
|
1 2 3 4 5 6 7 8 9 10
| $ /usr/bin/python3 Python 3.6.8 (default, Jan 14 2019, 11:02:34) [GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import sysconfig >>> sysconfig.get_config_var('SOABI') 'cpython-36m-x86_64-linux-gnu' >>> sysconfig.get_config_var('EXT_SUFFIX') '.cpython-36m-x86_64-linux-gnu.so' >>>
|
1 2 3 4 5 6 7 8 9 10
| $ /opt/runsisi/python3/bin/python3 Python 3.6.9 (default, Aug 29 2019, 07:53:04) [GCC 7.4.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import sysconfig >>> sysconfig.get_config_var('SOABI') 'cpython-36d-x86_64-linux-gnu' >>> sysconfig.get_config_var('EXT_SUFFIX') '.cpython-36d-x86_64-linux-gnu.so' >>>
|
其中,36
表示版本号 3.6,字母 m
, d
表示 Python 构建时的选项:
1 2 3
| --with-pydebug (d) --with-pymalloc (m) --with-wide-unicode (u)
|
需要注意的是,扩展模块必须与 Python 解释器的 ABI 匹配才能被加载:
1 2 3 4 5 6 7
| $ ls x.* x.cpython-36d-x86_64-linux-gnu.so $ /opt/runsisi/python3/bin/python3 -c 'import x' $ /usr/bin/python3 -c 'import x' Traceback (most recent call last): File "<string>", line 1, in <module> ModuleNotFoundError: No module named 'x'
|
参考资料
/MD, /MT, /LD (Use Run-Time Library)
https://docs.microsoft.com/en-us/cpp/build/reference/md-mt-ld-use-run-time-library?view=vs-2019
Description of the default C and C++ libraries that a program will link with when built by using Visual C++
https://support.microsoft.com/en-us/help/154753/description-of-the-default-c-and-c-libraries-that-a-program-will-link
PEP 3149 – ABI version tagged .so files
https://www.python.org/dev/peps/pep-3149/