【问题标题】:cpdef in Cython tutorials not workingCython 教程中的 cpdef 不起作用
【发布时间】:2016-05-25 19:00:09
【问题描述】:

我是 cython 的新手。我有一个源代码文件hello.pyx:

cdef extern from "math.h":
     cpdef double sin(double x)

而且,我的setup.py 文件是:

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

ext_modules=[
    Extension("hello",
              sources=["hello.pyx"],
              libraries=["m"] # Unix-like specific
    )
]

setup(
name = "Demos",
ext_modules = cythonize(ext_modules)
)

然后我将其编译为.so

但是,当我import hello 时,我没有得到hello.sin 功能。

那么教程中写的“这里有一个 Cython 模块,可以直接访问 Python 代码的 C sin() 函数:”的目的是什么?

我正在关注外部声明中的official tutorial

运行 cythoning 的结果:

Compiling hello.pyx because it changed.
Cythonizing hello.pyx
running build_ext
building 'hello' extension
gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall-Wstrict-prototypes -fPIC -I/pool/software/python/python27plus-ibm/include/python2.7 -c hello.c -o build/temp.linux-x86_64-2.7/hello.o
gcc -pthread -shared build/temp.linux-x86_64-2.7/hello.o -L/proj/dist/sandbox/miniconda/lib -lm -lpython2.7 -o /home/shaowu/Documents/cython_play/hello.so

【问题讨论】:

  • 所以模块被导入但是里面没有sin函数?如果你尝试访问hello.sin,你会得到一个AttributeError?
  • @Jim 正确。我做dir(hello)的时候,没有sin,不知道为什么……
  • 我会检查您使用的版本。我的印象是这是几年前添加的,所以您可能已经过时了。
  • 这可能是一个原因。我的 cython 版本是 0.20.2。

标签: cython


【解决方案1】:

正如@DavidW 所说,这很可能是由于您使用的是旧版本的 Cython。在版本 0.22 你的 setup.py 脚本中,根据文档,should look like this:

from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext

ext_modules=[
    Extension("demo",
              ["demo.pyx"],
              libraries=["m"]) # Unix-like specific
]

setup(
  name = "Demos",
  cmdclass = {"build_ext": build_ext},
  ext_modules = ext_modules
)

要么使用它,要么使用install the latest version

【讨论】:

    【解决方案2】:

    我的笔记本电脑没有问题,以下是我执行的步骤:

    • cd 到包含hello.pyxsetup.pytest.py 的目录
    • python setup.py build_ext --inplace
    • python test.py

    这会返回:

    ['__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '__test__', 'sin']
    0.479425538604203
    

    test.py 包含:

    import hello
    
    print(dir(hello))
    print(hello.sin(0.5))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-06
      • 1970-01-01
      • 2015-08-06
      • 2013-02-04
      • 1970-01-01
      • 2014-10-25
      • 1970-01-01
      相关资源
      最近更新 更多