toki doki skrev:
>
> """""
> from libcpp.vector cimport vector
>
> cdef vector[int] *vect=new vector[int]()
> vect.push_back(5)
> vect.push_back(6)
> print vect[0]
> """""
>
> gives the following error:
>
> """""
> print vect[0]
>          ^
> /home/toki/progs/cython13tests/bug1.pyx:6:10: Cannot convert
> 'vector<int>' to Python object
> """""
>
>   
That's not a bug. That is you not knowing C++.  vect[0] dereferences a 
pointer in your code. What you get is the an object of type vector<int> 
as Cython says, not an int contained in the vector.

You want to use the [] operator on an C++ object, not a C++ pointer, 
which means:

cdef vector[int] vect() # if Cython accept this
vect.push_back(5)
vect.push_back(6)
print vect[0]

Second, you should be flogged for calling new outside a class 
contructor. That will give you memory or resource leaks due to C++ 
exceptions skipping the call to delete. Therefore, new only belongs in 
constructors and delete only belongs in destructors. If you want dynamic 
allocation anywhere else, you use std::vector<>.

An no, you never allocate a std::vector with new. STL objects are to be 
put on the stack. They allocate memory from the heap on their own. If 
you want to control how they do their allocation, you specify a custom 
allocator as the last template argument.

And finally, when you use a std::vector as function argument, you pass 
references -- not pointers. That way operators like [] will continue to 
work as expected:

void foobar(std::vector<int> a); // ok but slow
void foobar(std::vector<int>& a); // ok
void foobar(std::vector<int> *a); // bad

C++ has more gotchas than you can believe. It takes at least 10 years to 
master. C, C#, Python and Java are a lot simpler, even if it may not 
seem so superficially.

Sturla




_______________________________________________
Cython-dev mailing list
[email protected]
http://codespeak.net/mailman/listinfo/cython-dev

Reply via email to