Cython中vector赋值

6 投票
1 回答
1056 浏览
提问于 2025-04-17 17:03

这是我的Cython程序

cdef struct Node:
    int v
    Node* next
    Node* pre

def f(int N):
    cdef:
        vector[Node*] narray
        int i
    narray.assign(N, 0)
    for i in xrange(N):
        narray[i] = 0

Cython编译的结果:

Error compiling Cython file:
------------------------------------------------------------
...
    cdef:
        vector[Node*] narray
        int i
    narray.assign(N, 0)
    for i in xrange(N):
        narray[i] = 0
             ^
------------------------------------------------------------

testLinkList.pyx:107:14: Compiler crash in AnalyseExpressionsTransform

但是我可以用 push_back() 在向量的末尾添加值,或者用 int 代替 Node*。这有什么问题呢?

1 个回答

2

你在用哪个版本的Cython?我用的是0.20.1版本,这段代码在我这里可以正常运行:

# distutils: language=c++

from libcpp.vector cimport vector

cdef struct Node:
    int v
    Node* next
    Node* pre

def f(int N):
    cdef:
        vector[Node*] narray
        int i
    narray.assign(N, NULL)
    for i in range(N):
        narray[i] = NULL

还有这个 setup.py 文件:

from distutils.core import setup
from Cython.Build import cythonize

setup(ext_modules=cythonize("test_vector.pyx"))

撰写回答