Cython:导入 .pyd 文件 returns 出错(缺少初始化函数?)

Cython : importing a .pyd file returns an error (lack of an init function ?)

我正在学习如何使用 Cython 高效地编译 Python 代码并使其更快。

这是我到目前为止所做的:

  1. 我创建了一个名为 math_code_python.py 的 Python 文件,并在其中放置了 4 个简单函数。
  2. 我将该文件保存为 math_code_cython.pyx
  3. 我创建了一个名为 setup.py 的安装文件。
  4. 我在 Command Prompt 中输入了 python C:\Users\loic\Documents\math_code\setup.py build_ext --inplace
  5. 我得到了一个名为 math_code_cython.cp36-win_amd64.pyd 的编译文件,我将其重命名为 math_code_pyd.pyd
  6. 最后,我创建了一个名为 test_math_code.pyd 的 Python 文件,其中只有 import math_code_pyd。当我执行这个文件时,我收到了这条消息:

    ImportError: dynamic module does not define module export function
    

我做了一些研究,感谢那些帖子,我明白我必须提供 init function:

我的问题是:我该怎么做?我是否必须像下面这样在 math_code_python.py 末尾放置一个函数?

def __init__(self):
    # something ?

我的Python版本:

Python 3.6.1 |Anaconda 4.4.0 (64-bit)| (default, May 11 2017, 13:25:24) [MSC v.1900 64 bit (AMD64)]

math_code_python.py

def fact(n):
    if n==0 or n==1:
        return 1
    else:
        return n*fact(n-1)

def fibo(n):
    if n==0 or n==1:
        return 1
    else:
        return fibo(n-1)+fibo(n-2)

def dicho(f, a, b, eps):
    assert f(a)*f(b) < 0
    while b-a > eps:
        M = (a+b)/2.
        if f(a) * f(M) > 0:
            a = M
        else:
            b = M
    return M

def newton(f, fp, x0, eps):
    u = x0
    v = u - f(u)/fp(u)
    while abs(v-u) > eps:
        u = v
        v = u - f(u)/fp(u)
    return v

setup.py

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

from Cython.Distutils import build_ext
from Cython.Build import cythonize

import numpy as np

setup(name = "maido",
      include_dirs = [np.get_include()],
      cmdclass = {'build_ext': build_ext},
      ext_modules = cythonize(r"C:\Users\loic\Documents\math_code\math_code_cython.pyx"),
      )

您的错误是重命名了 pyd 文件。当您调用 import math_code_pyd 时,它会专门查找 initmath_code_pyd (Python2) 或 PyInit_math_code_pyd (Python3).

当您使用 Cython 编译它时,它会生成一个与 .pyx 文件名匹配的函数(即 initmath_code_cythonPyInit_math_code_cython)。因此它没有找到它期望的功能。 您不必自己提供此功能 - Cython 会生成它。

只需将您的 .pyx 文件命名为您希望调用的模块即可,不要重命名 .pyd 文件。 (原则上你可以删除 .cp36-win_amd64 但它很有用而且是有原因的)。