在Cython中使用C库时出现错误

时间:2019-11-13 12:17:33

标签: python c++ cython

在Qt Creator中,我创建了一个小型库(在Python项目的“ Squaring”子文件夹中):

squaring.h:

int squaring(int a);

squaring.c:

#include "squaring.h"
int squaring(int a){
    return a * a;
}

在Eclipse中,我创建了一个尝试使用该库的Python项目(according to the instructions from the official website)

cSquaring.pxd:

cdef extern from "Squaring/squaring.h":
    int squaring(int a)

Functions.pix:

cimport cSquaring
cpdef int count(int value):
    return cSquaring.squaring(value)

setup.py:

from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
setup(ext_modules=cythonize([Extension("Functions", ["Functions.pyx"])]))

main.py:

from Functions import count
if __name__ == '__main__':
    data = 1
    returned = count(data)
    print(returned)

使用(没有任何错误)完成C代码的编译:

python3 setup.py build_ext -i

但是当我在执行时运行main.py时,出现ImportError:

File “/home/denis/.p2/pool/plugins/org.python.pydev.core_7.3.0.201908161924/pysrc/pydevd.py”, line 2643, in <module>
main()
File “/home/denis/.p2/pool/plugins/org.python.pydev.core_7.3.0.201908161924/pysrc/pydevd.py”, line 2636, in main
globals = debugger.run(setup, None, None, is_module)
File “/home/denis/.p2/pool/plugins/org.python.pydev.core_7.3.0.201908161924/pysrc/pydevd.py”, line 1920, in run
return self._exec(is_module, entry_point_fn, module_name, file, globals, locals)
File “/home/denis/.p2/pool/plugins/org.python.pydev.core_7.3.0.201908161924/pysrc/pydevd.py”, line 1927, in _exec
pydev_imports.execfile(file, globals, locals) # execute the script
File “/home/denis/.p2/pool/plugins/org.python.pydev.core_7.3.0.201908161924/pysrc/_pydev_imps/_pydev_execfile.py”, line 25, in execfile
exec(compile(contents+“\n”, file, ‘exec’), glob, loc)
File “/home/denis/eclipse-workspace/ConnectionWithCPlusPlus/main.py”, line 1, in <module>
from Functions import count
ImportError: /home/denis/eclipse-workspace/ConnectionWithCPlusPlus/Functions.cpython-37m-x86_64-linux-gnu.so: undefined symbol: squaring

另一个使用代码Cython的项目(我没有创建C语言库,而是直接在Cython上编写了代码)工作正常。

出什么问题了?

1 个答案:

答案 0 :(得分:1)

您将头文件包含在Cython中,但您从未真正告诉过它实现,即定义函数的库。您需要链接到Cython docs中所述的通过编译C源代码生成的库。

Functions.pyx中,您必须在顶部添加这样的评论。

# distutils: sources = path/to/squaring.c