python - 我可以将 Cython 代码转换为 Python 吗?

标签 python cython

我编写了一个 cython 代码来帮助弥合 3rdparty 库和 python 之间的差距。

我还在 cython 中编写了一些代码以提高其性能。

我可以将上述两个用例转换为原始 python 吗?

用例一示例

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

用例 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!

最佳答案

对于您的第一个用例,答案是肯定的。 您需要做的就是像这样删除 cdef 行。

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

对于第二个用例,事情变得棘手,因为您不能只删除 cdef 行或将 cdef 重命名为 def。此外,由于此用例依赖于外部库,因此它没有直接到 python 的翻译。

除了 Cython 之外,您还有 2 个选项可以使用。

  • ctypes - 标准 Python 中内置的外部函数库
  • cffi - 一个与 ctypes 类似的库,但简化了库粘合代码。

使用 ctypes 的使用示例如下所示

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))

您使用 cffi 的使用示例如下所示

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)

关于python - 我可以将 Cython 代码转换为 Python 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47687633/

相关文章:

python - 如何从 Django rest 框架的序列化程序中获取特定字段

Python:从迭代器内的列表中删除元素?

python - 从语言环境代码中获取本地化语言名称

python - Pycharm 错误 - 没有名为 MySQLdb 的模块

python - 为什么我会收到此错误以及如何修复它?

python - 如何解析对象数组的 JSON 结果并在 Excel 中打印?

python - 如何在 setup.py 中为 cython 设置 sysroot

python - 是否值得用 cython 重写我的代码?

c++ - Cython 和 C++ 继承

cython - 在 Cython 中定义字符串数组