【问题标题】:Cython: Linked List of Extension TypeCython:扩展类型的链接列表
【发布时间】:2021-12-17 14:25:25
【问题描述】:

我需要一个使用 Cython 扩展类型的链表,即。 cdef class 但 Cython 编译器抱怨 Python 对象。

cdef class Item:
    cdef Item* prev
    cdef Item* next

Cython 错误:Pointer base type cannot be a Python object

应该是cdef struct,但是使用cdef class 有什么解决方法吗? (因为我需要方法和 OOP 约定)

【问题讨论】:

  • 您可以使用C++ class。另请注意,Cython 包装了大部分 C++ STL,包括 std::list<T>,请参阅 here。所以真的不需要重新发明轮子。

标签: python class pointers struct cython


【解决方案1】:

cdef class 与任何其他 Python 对象一样,通过引用存储/传递。

这意味着这里不需要使用指针:内部表示已经与指针一起存储。因此只需使用cdef Item

与任何其他 Python 对象一样,您的 Item 将被引用计数,并在不存在其他引用时自动重新分配。

【讨论】:

  • @Dave 直接使用cdef Item prev,next 时,我遇到了问题,因为prevnext 是在init 中创建的,并且会发生无限递归
  • cdef Item 真正的意思是“Item or None”) 所以你可以给它分配None 来终止无限递归
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-19
  • 2017-11-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多