簡體   English   中英

導入cython函數:AttributeError:'module'對象沒有屬性'fun'

[英]Importing cython function: AttributeError: 'module' object has no attribute 'fun'

我寫了一個小的cython代碼

#t3.pyx
from libc.stdlib cimport atoi

cdef int fun(char *s):
        return atoi(s)

setup.py文件是

from distutils.core import setup
from Cython.Build import cythonize

setup(ext_modules=cythonize("t3.pyx"))

我使用此命令運行setup.py

python setup.py build_ext --inplace

這給了我

Compiling t3.pyx because it changed.
Cythonizing t3.pyx
running build_ext
building 't3' extension
x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-     prototypes -fno-strict-aliasing -D_FORTIFY_SOURCE=2 -g -fstack-protector-  strong -Wformat -Werror=format-security -fPIC -I/usr/include/python2.7 -c    t3.c -o build/temp.linux-x86_64-2.7/t3.o
t3.c:556:12: warning: ‘__pyx_f_2t3_fun’ defined but not used [-Wunused-function]
 static int __pyx_f_2t3_fun(char *__pyx_v_s) {
        ^
x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security -Wl,-Bsymbolic-functions -Wl,-z,relro -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security build/temp.linux-x86_64-2.7/t3.o -o /home/debesh/Documents/cython/t3/t3.so

當我在python解釋器中運行時它向我顯示

>>> import t3
>>> t3.fun('1234')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'fun'
>>> 

這里的問題是你用cdef而不是def來定義你的方法。 cdef方法只能從cython代碼中調用。

您可以在文檔的Python函數與C函數部分中找到詳細信息。

Python函數是使用def語句定義的,就像在Python中一樣。 它們將Python對象作為參數並返回Python對象。

C函數使用新的cdef語句定義。 它們將Python對象或C值作為參數,並且可以返回Python對象或C值。

而重要的部分:

在Cython模塊中,Python函數和C函數可以自由地相互調用,但只能通過解釋的Python代碼從模塊外部調用Python函數。 因此,您希望從Cython模塊“導出”的任何函數都必須使用def聲明為Python函數。

暫無
暫無

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

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