Cython:从 .pyx 文件导入定义

Cython: Import definitions from .pyx file

我有 1 个 Cython .pxd 文件和 1 个 Cython .pyx 文件,pyx 文件包含 cdef class:

# myclass.pyx (compiled to myclass.so)
cdef class myclass:
   pass

现在是另一个功能的.pxd文件

# another.pxd (with another.pyx along)
from libcpp.vector cimport vector
import myclass # This line is funny, change 'myclass' to whatever and no syntax error

cdef vector[myclass] myvar # COMPILE TIME ERROR
cdef myclass myvar2        # SIMPLER, STILL COMPILE TIME ERROR

当编译 another.pyx 时,Cython 显示关于 vector[myclass] 的错误,它说 'myclass' 是未知的。为什么会这样?

应该这样描述清楚:

  • myclass.pyx编译成.so文件
  • 但是.so文件中有2种东西
    • Python 定义:只能使用 'import'
    • 导入
    • Cython 定义:只能使用 'cimport'
    • 导入

问题是 another.pxd 中的 import myclass 不会导入 myclass 因为它是 cdef(Cython 定义)。

在 another.pxd 文件中,要导入 'myclass',必须是:

  • from myclass cimport myclass
    • myvar2 将是:cdef myclass myvar2
  • cimport myclass
    • myvar2 将是:cdef myclass.myclass myvar2
  • cimport some.path.to.myclass as myclass
    • myvar2 将是:cdef myclass myvar2

导出也可能存在问题,尤其是使用 Python 构建工具而不是直接使用 cython3gcc

  • __pyx_capi__在.so文件中不可用
  • myclass 不是 public 并且在导入后看不到

因此最好将 myclass 置于 myclass.pyx 的 public 范围内:

cdef public:
    class myclass:
        pass