我刚刚设法为 Python 构建了我的第一个 C 扩展,使用 Cython 调用现有的 C 库。
我将我的数据类型和函数声明并定义为逻辑组件(遵循 C 库的逻辑结构),并将它们组合到一个 pyx 文件中 - 在我尝试单独添加文件时发生错误之后(IIRC 我得到了一个错误按照已经定义的 init 行——在谷歌上研究了这个问题之后,我发现我必须将所有 pyx 文件信息合并到一个 pyx 文件中)——参见这个链接。
这是我的 foo.pyx 文件内容的副本:
#include "myarray.pyx"
#include "myset.pyx"
#include "mycalc.pyx"
这是我的设置文件的副本:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
setup(
cmdclass = {'build_ext': build_ext},
ext_modules = [Extension("foo", ["foo.pyx"],
libraries=["foo_core"])
]
)
扩展成功构建到 foo.so 中,然后我可以在 Python CLI 中键入“import foo”。这也有效。但是,当我尝试访问我在 myarray.pxd、myarray.pyx 等中声明/定义的任何类时,我收到错误消息:
AttributeError: 'module' object has no attribute 'myArray'
然后我尝试了 dir(),看看 foo 模块正在导出什么。令我惊讶的是,这就是它列出的内容:
>>> dir(foo)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__test__']
为什么 Cython 无法导出我声明和定义的结构、类和函数?我认为我的 pxd 和 pyx 文件没有任何问题,因为就像我说的,它编译成功并且生成了共享库(python 扩展)。
我在 Ubuntu 上使用 Cython 0.15.1 和 Python 2.6.5