从Python调用Cython C函数 [英] Calling Cython C functions from Python

查看:302
本文介绍了从Python调用Cython C函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Cython 文件,名为 foo.pyx 包含以下功能:

I have a Cython file called foo.pyx containing the following functions:

def add_one(int n):
    cdef int m = n + 1
    return m

cdef int c_add_one(int n):
    return n + 1

我使用 cython -a foo.pyx <构建此 pyx 文件/ code>然后可以执行以下操作:

I build this pyx file using cython -a foo.pyx and can then do:

>>> import foo
>>> foo.add_one(5)
6
>>> foo.c_add_one(5)
AttributeError: 'module' object has no attribute 'c_add_one'

所以看起来我无法从python调用 c_add_one 。使用 cdef 声明函数有什么好处?

So it looks like I can't call c_add_one from python. What are the advantages of declaring a function using cdef?

推荐答案


  1. 速度:Cython和C可以调用 cdef cpdef 函数比常规功能快得多。常规 def 函数是成熟的Python对象。它们需要引用计数,GIL等。

  2. 封装:如果函数声明为 cdef ,它不会向Python用户公开。如果该功能从未打算供公众使用(例如,因为它不检查其参数或与将来可能会更改的实现细节有关),则这将是有益的。用户当然仍然可以通过C / Cython来规避这一点,但是这样做比大多数人都更麻烦。这样,就类似于双下划线名称修饰。

  1. Speed: Cython and C can call cdef and cpdef functions much faster than regular functions. Regular def functions are full-blown Python objects. They require reference counting, the GIL, etc.
  2. Encapsulation: If a function is declared cdef, it will not be exposed to Python users. This is beneficial if the function was never intended for public consumption (e.g. because it doesn't check its parameters, or relates to an implementation detail which might change in the future). Users can still circumvent this via C/Cython, of course, but doing so is more of a hassle than most will bother with. In this way, it's similar to double-underscore name mangling.

这篇关于从Python调用Cython C函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆