前文參見 《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