如何打包分发使用共享库的python模块?

时间:2014-06-10 16:59:34

标签: python ctypes setuptools distutils

我正在为C库编写一些绑定,并且我不确定如何配置所有这些以进行分发,因此可以pip install我的包。

我们说我有以下文件:

  • library.c
  • library.h
  • wrapper.py

为了让我的包装库工作,有必要:

  • 编译library.c并创建共享库
  • ctypesgen上运行library.h以生成ctypes代码

以下是命令:

  • gcc -Wall -fPIC -c library.c
  • gcc -shared -Wl,-soname,liblibrary.so.1 -o liblibrary.so.1.0 library.o
  • ctypesgen.py library.h -L ./ -l library -o _library.py

运行setup.py还取决于用户已安装ctypesgen

我不知道如何设置这一切,以便对图书馆感兴趣的人可以简单pip install library并自动完成所有这些。有人能帮忙吗?

1 个答案:

答案 0 :(得分:2)

您需要的是setuptools / distutils的扩展功能。

Documentation has more information,简而言之,上面的示例setup.py看起来如下所示

from setuptools import setup, find_packages, Extension

extensions = [Extension("my_package.ext_library",
                       ["src/library.c"],
                       depends=["src/library.h"],
                       include_dirs=["src"],
              ),
]
setup(<..>,
     ext_modules=extensions,
)

.so在构建模块时由setup.py自动生成。如果需要链接到其他库,可以向扩展提供libraries参数列表。有关详细信息,请参阅文档(1)。

由于这是在setuptools的功能中构建的,因此它可以与pip一起使用,并且可以在pypi上分发(仅作为源代码)。 Extension引用的所有源文件必须存在于分布式pypi存档中。

如果您想构建可分发的二进制轮子,包括本机代码see manylinux

相关问题