python - 导入cython函数: AttributeError: 'module' object has no attribute 'fun'

标签 python cython

我写了一个小的 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 functions vs. C functions 中找到详细信息文档部分。

Python functions are defined using the def statement, as in Python. They take Python objects as parameters and return Python objects.

C functions are defined using the new cdef statement. They take either Python objects or C values as parameters, and can return either Python objects or C values.

重要的部分:

Within a Cython module, Python functions and C functions can call each other freely, but only Python functions can be called from outside the module by interpreted Python code. So, any functions that you want to “export” from your Cython module must be declared as Python functions using def.

关于python - 导入cython函数: AttributeError: 'module' object has no attribute 'fun' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30228821/

相关文章:

struct - 如何从cython中的dict初始化结构

cython - 如何在 Cython 中扩展宏

python - 在 cython 中指定大于 long double 的数字

python - 同名的相对和绝对导入导致 "AttributeError: ' 模块'对象没有属性...”

python - 在 Python 中使用模块 PICKLE 打开 Matlab 文件 .mat

python - 提高连体网络的准确性

python - 如何为 gedit 编写 python 命令?

python - 在 Cython 类中,使用 __init__ 和 __cinit__ 有什么区别?

python - 指针作为扩展类型 cython 中的属性

python - 安装并使 tkinter 在 AWS EC2 实例上工作