簡體   English   中英

將 C 庫與 Cython 一起使用時出現錯誤

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

在 Qt Creator 中,我創建了一個小型庫(在 Python 項目的“平方”子文件夾中):

平方.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"])]))

主要.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 中包含了 header 文件,但您從未真正告訴它實現,即定義 function 的庫。 您需要鏈接到通過編譯 C 源代碼生成的庫,如Cython 文檔中所述。

在您的Functions.pyx中,您必須在頂部添加這樣的評論。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM