【问题标题】:python - How to use python call function in pyx filepython - 如何在 pyx 文件中使用 python 调用函数
【发布时间】:2014-01-22 00:20:13
【问题描述】:

我是 cython 的新手。

现在,我正在尝试导入标准 c 库并在 pyx 文件中定义一个简单的函数:

from libc.math cimport sin

cdef double f(double x):
    return sin(x*x)

我用这个文件编译:

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
)

并生成一个名为 demo.so 的库 现在我试图在 python 文件中调用这个“f”函数:

import demo
print demo.f(2)

编译器说,

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

有谁知道,如何调用 pyx 文件中的函数?谢谢!

【问题讨论】:

    标签: python cython


    【解决方案1】:

    cdef定义的函数不能从python访问。您可以编写它们并在 cython 代码中使用它们,但它们不能暴露。

    如果你想公开一个函数,要么用def定义它,要么用cpdef定义它。

    使用 def 您将创建一个普通的 python 函数,这意味着在 cython 代码中使用该函数可能需要比使用 cdef 更多的转换(因此需要更多的开销)。

    使用cpdef cython 将生成两个函数。一个是完全使用cdef 定义的函数,它还将创建一个python 函数作为该函数的包装器。 cython 代码将使用函数的纯 C 版本,从而减少开销,并且库将暴露包装器。

    【讨论】:

    • 感谢您的评论,真的很有帮助
    猜你喜欢
    • 2011-11-22
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多