Jfm Meyers
Jfm Meyers

Reputation: 133

Can I convert my Cython code to Python?

I have written a cython code to help bridge the gap between a 3rdparty library and python.

I also written some of my code in cython to improve its performance.

Can I convert both of my above use cases into raw python?

example of use case one

def f(double x):
    return x**2-x

def integrate_f(double a, double b, int N):
    cdef int i
    cdef double s, dx
    s = 0
    dx = (b-a)/N
    for i in range(N):
        s += f(a+i*dx)
    return s * dx

example of use case 2

from libc.stdlib cimport atoi

cdef parse_charptr_to_py_int(char* s):
    assert s is not NULL, "byte string value is NULL"
    return atoi(s)   # note: atoi() has no error detection!

Upvotes: 1

Views: 2711

Answers (1)

Jfm Meyers
Jfm Meyers

Reputation: 133

Well for you first use case the answer is yes. All you would need to do is remove the cdef lines like so.

def f(double x):
    return x**2-x

def integrate_f(double a, double b, int N):
    s = 0
    dx = (b-a)/N
    for i in range(N):
        s += f(a+i*dx)
    return s * dx

For your second use case that's where things get tricky because you cant just delete the cdef lines or rename cdef to def. Also since this use case depends on the external library it doesn't have direct to python translation.

You have 2 options you can use besides Cython.

  • ctypes - the foreign function library built into standard python
  • cffi - a library that works similar to ctypes but simplifies the library glue code.

Your usage example using ctypes would look like this

def parse_charptr_to_py_int(test):
    from ctypes import cdll,c_char_p
    cdll.LoadLibrary("libc.so")
    return cdll.libc.atoi(c_char_p(test))

Your usage example using cffi would look like this

def parse_charptr_to_py_int(test):
    from cffi import FFI
    ffi = FFI()
    ffi.cdef("int atoi(const char *str);")
    CLib = ffi.dlopen("libc.so")
    return CLib.atoi(test)

Upvotes: 2

Related Questions