我已经完全复制了Cython文档中关于封装C++类的示例代码。我可以通过使用distutils
和cythonize()
方法成功构建并导入rect.so
扩展,即:
Putting the following directives at the top of
rect.pyx
:# distutils: language = c++ # distutils: sources = Rectangle.cpp
Writing a
setup.py
file that contains this:from distutils.core import setup from Cython.Build import cythonize setup( name = "rectangleapp", ext_modules = cythonize('*.pyx'), )
Calling
$ python setup.py build_ext --inplace
然而,当我在Cython中包装C代码时,我经常发现手动从命令行编译单个扩展更加方便,即:
Generate the
.c
code using the command line Cython compiler$ cython foo.pyx
Manually compile it using
gcc
:$ gcc -shared -fPIC -O3 -I /usr/lib/python2.7 -L /usr/lib/python2.7 \ foo.c -lpython2.7 -o foo.so
我尝试将相同的过程应用于构建上述rect.so
示例:
$ cython --cplus rect.pyx
$ g++ -shared -fPIC -O3 -I /usr/lib/python2.7 -L /usr/lib/python2.7 \
rect.cpp -lpython2.7 -o rect.so
看起来Cython和g++编译步骤都成功了 - 我没有得到任何命令行输出,并且最后我有一个构建好的rect.so
文件。然而,当我尝试导入模块时,我会遇到一个undefined symbol
错误:
In [1]: import rect
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-1-ba16f97c2145> in <module>()
----> 1 import rect
ImportError: ./rect.so: undefined symbol: _ZN6shapes9Rectangle9getLengthEv
如何手动编译包装C++类的Cython代码的正确步骤?
gcc -shared -fPIC -IC:\Users\python37\include -LC:\Users\python37\libs rect.cpp Rectangle.o -lstdc++ -o rect.pyd -lpython37
但是,当我在Python中执行import rect
时,现在出现了ImportError: DLL load failed: The specified procedure could not be found.
。有任何想法吗? - A.P.