使用 distutils 将 C 代码集成到 Python 库中的最传统方法是什么?

问题描述

许多著名的 Python 库基本上都是用 C 编写的(如 tensorflow 或 numpy),因为这显然大大加快了速度。通过阅读this,我能够非常轻松地将C 函数集成到python 中。 这样做我终于可以使用 distutils 访问 source.c 文件功能

# setup.py

from distutils.core import setup,Extension

def main():
    setup(
        # All the other parameters...
        ext_modules=[ Extension("source",["source.c"]) ]
        )

if __name__ == "__main__":
    main()

这样当我运行 python setup.py install 时,我可以安装我的库。 但是,如果我想为 source.c 中的函数创建一个 python 编码的包装对象怎么办?有没有办法在不污染已安装模块的情况下做到这一点?
在互联网上闲逛时,我看到了一些使用共享库 (.so) 的看似简单的解决方案。但是,我需要一个不涉及附加编译的 C 代码解决方案,而是一个在程序第一次运行时对其进行编译的解决方案。

解决方法

在这种情况下,共享库是正确的方法。 distutils 具有构建静态库的能力,如下所示:

from distutils.ccompiler import new_compiler
from distutils import sysconfig

c = new_compiler()
workdir = "."
c.add_include_dir( sysconfig.get_python_inc() )
c.add_include_dir("./include")
objects = c.compile(["file1.c","file2.c"])
c.link_shared_lib(objects,"mylibrary",output_dir=workdir)

这将在工作目录中生成 .so 库。

例如它在实际中的使用方式 setup 参见 following example