Python 如何将代码打包成 SO 文件

现在需要将 Python 源码打包成 SO 文件,然后给再用 Python 调用这个生成的 SO 文件。

我查了一些资料,例如 https://www.cnblogs.com/ke10/p/py2so.html,然后照着生成了 SO 文件,接着在使用 ctypes 调用的时候出了问题,报错 AttributeError: build/lib.linux-x86_64-3.6/test.cpython-36m-x86_64-linux-gnu.so: undefined symbol: np_add

test.py 文件:

import numpy as np

def np_add(x, y): return x + y

if name == “main”: x = 1 y = 2 print(f"{x} + {y} = {np_add(x, y)}")

setup.py 文件:

from distutils.core import setup
from Cython.Build import cythonize

setup(ext_modules=cythonize(“test.py”))

各位有什么建议吗?或者说不采取这种方法,有其他经过试验的方法可以成功打包并成功调用的吗?

希望过来人给点建议,先谢谢了。


Python 如何将代码打包成 SO 文件

4 回复

要打包成 .so 文件,用 Cython 最直接。先装 Cython:pip install cython

假设你有个 my_module.pyx 文件,内容如下:

# my_module.pyx
def hello_world():
    print("Hello from .so!")

然后创建 setup.py

from setuptools import setup
from Cython.Build import cythonize

setup(
    ext_modules = cythonize("my_module.pyx")
)

最后在终端运行:

python setup.py build_ext --inplace

这会在当前目录生成 my_module.cpython-xxx.so,其他 Python 程序就能直接 import my_module 了。如果代码里有纯 Python 对象,Cython 会自动处理转换,但复杂类型可能需额外类型声明。

总结:用 Cython 编译 .pyx 文件最省事。

我在 win 下是编译成功的, 你的环境里可能没有安装 swig. which swig 你检查一下

而且似乎你写了一条没有用的语句: if name == “main” ,这是无效的, 既然已经用了 cython, 则不存在 main 的入口.

我没有使用你的 setup.py ,你修改下试试。
from distutils.core import setup, Extension
import numpy

np = Extension(‘test’, sources=[‘test.py’],
include_dirs=[numpy.get_include()])
setup(ext_modules=[np])

回到顶部