【问题标题】:Cython: Import definitions from .pyx fileCython:从 .pyx 文件导入定义
【发布时间】:2021-12-14 09:16:24
【问题描述】:

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

# 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”是未知的。为什么会这样?

【问题讨论】:

  • 你所做的永远不会奏效——你不能制作一个 cdef 类的向量。 cdef 类是一个 Python 对象,因此需要引用计数,而 vector 根本无法做到这一点。
  • @DavidW 好难过,所以 .pxd 文件中只允许使用 c/c++ 类型?
  • 没有。您可以在 pxd 文件中使用 cdef 类。您不能将它们存储在 C++ 向量中。
  • .pxd 文件只能包含编译时的东西。因此它需要是cimport myclass。这也意味着应该有一个myclass.pxd(因为cimport 寻找一个pxd 文件,而不是一个pyx 文件)
  • 那是因为import myclass 发生在运行时。 .pxd 文件应该包含编译时cimport myclass(或者可能是cimport myclass from myclass

标签: python c++ import compiler-errors cython


【解决方案1】:

应该这样清楚地描述:

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

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

在另一个.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 不公开,导入后看不到

因此最好将 myclass 置于 myclass.pyx 中的公共范围内:

cdef public:
    class myclass:
        pass

【讨论】:

    猜你喜欢
    • 2021-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多