填坑 CentOS7 使用 Python3 安装 Cython 编写扩展

前文参见 《CentOS 7 下通过 Cython 编写 python 扩展 》, 用的是 Python2.7,本文用的是 Python3.6

yum install python3 python3-devel gcc
pip3 install Cython -i https://pypi.tuna.tsinghua.edu.cn/simple

创建 pyx 文件与前文一致

python3 setup.py -build_ext --inplace 

如遇到出错,报告

hello.c:2264:3: error: ‘for’ loop initial declarations are only allowed in C99 mode

表示当前的 gcc 4.8.5 默认仅支持 C89 标准, 不兼容在 for 中定义循环变量,搜索一圈没找到如何在 setup.py 中传参支持 -std=c99,ChatGPT 倒是给了个方案

from setuptools import setup, Extension
extensions = [Extension("your_module", ["your_module.pyx"], extra_compile_args=["-std=c99"])]
etup(
    ext_modules=extensions,
    # other setup parameters...
)

可惜运行下来还是一样的错误,还尝试过添加文件头

# distutils: language=c++
# distutils: define_macros=PY_SSIZE_T_CLEAN
# cython: language_level=3
# cython: extra_compile_args=['-std=c99']


也不解决问题。好在已经生成了 hello.c,于是参考控制台输出自己手动完成后续编译

gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -O2 \
-g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions \
-fstack-protector-strong --param=ssp-buffer-size=4 \
-grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE \
-fPIC -fwrapv -fPIC -I/usr/include/python3.6m -c hello.c -o \
hello.o -std=c99

不错,生成了 hello.o 之后,再通过

gcc -shared hello.o -o hello.so

终于得到了 hello.so 文件,运行调用

python3 hello.py

输出 

Hello cython

尝试通过Python2 调用会报错

python hello.py 
ImportError: /root/hello_pack/hello.so: undefined symbol: _Py_FalseStruct

应该是不兼容 Python2

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章