[Cython] wrapping c++
William Stein
wstein at gmail.com
Tue Mar 4 15:54:11 CET 2008
On Tue, Mar 4, 2008 at 6:39 AM, Neal Becker <ndbecker2 at gmail.com> wrote:
> I've made some progress on learning to wrap std::vector. I've got a
> __getitem__, but I don't know what to do about __setitem__.
> cdef extern from "vector":
> pass
>
> cdef extern from "test1.hpp":
> ctypedef struct intvec "std::vector<unsigned int>":
> void (* push_back)(int elem)
> inline int get "operator[]" (int i)
>
> intvec intvec_factory "std::vector<unsigned int>"(int len)
>
> int my_sum "my_sum<std::vector<unsigned int> >"(intvec vec)
>
>
>
> cdef intvec v = intvec_factory(2)
> v.push_back(2)
>
> #print my_sum (v)
>
> cdef class intvec_wrap:
> cdef intvec vec
> def __init__(self):
> self.vec = intvec_factory (2)
> def __getitem__(self, int i):
> return self.vec.get (i)
>
> Problem is, operator[] (or at()) returns an int&. I don't have a clue what
> to do with this.
There is an example of doing setitem directly in Cython with
std::vector<unsigned int>
using C name specifiers in my talk on Cython at Enthought from two
days ago. See
the talk listed at the bottom of this page:
http://wiki.sagemath.org/days8/schedule
Here's the example:
cdef extern from "vector.h":
ctypedef unsigned long size_type
ctypedef struct intvec "std::vector<unsigned int>":
int get_entry "operator[]"(int n)
size_type size()
intvec intvec_factory "std::vector<unsigned int>"(int len)
cdef extern from "":
void DEFINE_SET "#define SET(a,b,c) a[b]=c; //"()
void SET(intvec, int, int)
DEFINE_SET()
cdef intvec v = intvec_factory(10)
SET(v,2,5)
print v.get_entry(2)
print v.size()
----------------
The key thing is the evil dirty trick to define a SET macro directly in Cython.
-- William
More information about the Cython-dev
mailing list