gpt4 book ai didi

python - 使用 distutils 将 C 代码集成到 Python 库中的最常规方法是什么?

转载 作者:行者123 更新时间:2023-12-03 17:24:39 25 4
gpt4 key购买 nike

许多著名的 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工作目录中的库。
例如它在实际中的使用方式 setupfollowing example

关于python - 使用 distutils 将 C 代码集成到 Python 库中的最常规方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66498069/

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