Allocate an array of vectors in Cython?

493 views
Skip to first unread message

Wenxiang Chen

unread,
May 1, 2012, 6:50:42 PM5/1/12
to cython...@googlegroups.com
Hi All,

I am new to Cython. I have tried a couple of different approaches, yet I still failed to allocate an array of vectors.

The first method I have tried is 
"cdef vector[int] stack[10]"
The cython compiler showed:
    #Error compiling Cython file:
    #------------------------------------------------------------
    #...
    #    void* malloc(size_t size)
    #    void* realloc(void* ptr, size_t size)
    #
    #def vecTest(self):
    #    cdef int n = 10
    #    cdef vector[int] stack[10]
    #                          ^
    #------------------------------------------------------------
    # arrOfVec.pyx:10:27: Template parameter not a type.


The second method which I also tried is:
    cdef vector[int]* arr
    arr = <vector[int] *> malloc(sizeof(vector[int])*n)
It still cannot pass the compilation. The error message is shown below:
    #Error compiling Cython file:
    #------------------------------------------------------------
    #    arr = <vector[int] *> malloc(sizeof(vector[int])*n)
    #                      ^
    #------------------------------------------------------------
    #
    #arrOfVec.pyx:27:23: Unknown type

The minimal code reproducing the error is attached as "arrOfVec.pyx", the setup file is attached as well.

Could you guys show me some hints on how to fix this issue? Many thanks in advance.

- Wenxiang
arrOfVec.pyx
testSetup.py

Robert Bradshaw

unread,
May 2, 2012, 2:33:18 AM5/2/12
to cython...@googlegroups.com
It looks like there's a bug in trying to allocate an array of
templated types, but the following works for me (Cython 0.16).

from libcpp.vector cimport vector
from libc.stdlib cimport malloc

def test(int n):
cdef vector[int] *stack
stack = <vector[int] *> malloc(sizeof(vector[int])*n)

- Robert

Wenxiang Chen

unread,
May 2, 2012, 1:28:42 PM5/2/12
to cython...@googlegroups.com
Thanks Robert. 

I used Cython 0.15.1 shipped with Fedora 16, that could be the reason why " stack = <vector[int] *> malloc(sizeof(vector[int])*n) " didn't work.

I have manually installed Cython 0.16. The compilation goes smoothly now.

-Wenxiang
Reply all
Reply to author
Forward
0 new messages