在Cython中使用C库时,我遇到了一个错误

I get an error, when using C-library with Cython

本文关键字:错误 一个 遇到 Cython 库时      更新时间:2023-10-16

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

平方。h:

int squaring(int a);

平方。c:

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

在Eclipse中,我创建了Python项目,尝试使用这个库(根据官方网站上的说明(:

cSquaring.pxd:

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

函数.pix:

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

设置.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上编写代码(运行良好。

问题出在哪里?

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

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

# distutils: sources = path/to/squaring.c
相关文章: