Calling Cython C Functions from Python

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 

I create this pyx file using cython -a foo.pyx and can:

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

So it looks like I cannot call c_add_one from python. What are the benefits of declaring a function with cdef ?

+5
source share
1 answer
  • Speed : Cython and C can call cdef and cpdef much faster than regular functions. Regular def functions are full-blown Python objects. They require reference counting, GIL, etc.
  • Encapsulation . If a cdef function is declared, it will not be available to Python users. This is useful if the function was never intended for public consumption (for example, because it does not check its parameters or is not connected with an implementation detail that may change in the future). Of course, users can get around this through C / Cython, but doing it more likely because of the hassle than most will worry. Thus, it looks like a double naming convention.
+4
source

Source: https://habr.com/ru/post/1206174/


All Articles