在Cython中创建对象列表

3 投票
1 回答
3756 浏览
提问于 2025-04-17 15:25

我想知道如何在Cython中创建一个C语言对象的列表。

这个简单的例子可以正常工作:

cimport cython

b = real_test()
print(b)

cdef real_test():
    cdef int a
    cdef Node b = Node()
    a = b.h
    return a

cdef class Node:
    cdef int h
    def __cinit__(self):
        self.h = 3

但是这个就不行:

cimport cython

b = real_test()
print(b)

cdef real_test():
    cdef int a
    cdef Node *b = [Node(),Node(),Node()]
    a = b[0].h
    return a

cdef class Node:
    cdef int h
    def __cinit__(self):
        self.h = 3

该怎么做呢?

谢谢!

1 个回答

1

我不太确定这样做是否正确,但它确实有效:

cimport cython

b = real_test()
print(b)

cdef real_test():
    cdef int a
    cdef list b = [Node(),Node(),Node()]
    a = b[0].h
    return a

cdef class Node:
    cdef int h
    def __cinit__(self):
        self.h = 3
    property h:
        def __get__(self):
          return self.h
        def __set__(self, float value):
          self.h = value

撰写回答