Convert Python dictionary to C++ map of objects

1,048 views
Skip to first unread message

Francisco Paisana

unread,
Dec 4, 2014, 2:54:47 PM12/4/14
to cython...@googlegroups.com
Hello everyone,

I started using Cython today to wrap my C++ code and I run into a problem, for which I didn't find any solution.

Considering I have two C++ classes, A and B, and the following Python respective PyA and PyB classes,

cdef class PyA:
    cdef A *thisptr
    def __cinit__(self):
         self.thisptr = new A()
    def __dealloc__(self):
         del self.thisptr
     (...)

cdef cppclass PyB:
    cdef B *thisptr
    def __cinit__(self):
         self.thisptr = new B()
    def __dealloc__(self):
         del self.thisptr
    def process(self, map[int, A] a):
        self.thisptr.process(a)

Considering that the function PyB.process() receives a C++ type map I would expect Cython to convert it automathically like std::map <=> dict. However, I get this message:

Cannot convert Python object argument to type 'map[int,A]'

Which leads me to think that Cython does not know how to convert a dictionary with PyA objects to a C++ map with A objects (which is understandable). Would you know a way to make this work (preferably clean and easy)?

Thanks for your help in advance!

Regards,
Francisco

Sturla Molden

unread,
Dec 5, 2014, 5:30:55 AM12/5/14
to cython...@googlegroups.com
On 04/12/14 20:54, Francisco Paisana wrote:

> cdef cppclass PyB:
> cdef B *thisptr
> def __cinit__(self):
> self.thisptr = new B()
> def __dealloc__(self):
> del self.thisptr
> def process(self, map[int, A] a):
> self.thisptr.process(a)


> Which leads me to think that Cython does not know how to convert a
> dictionary with PyA objects to a C++ map with A objects (which is
> understandable). Would you know a way to make this work (preferably
> clean and easy)?


Something like this? (Not tested)


def process(PyB self, dict a):
cdef map[int, A] *ma
cdef PyA pya
try:
ma = new map[int, A]()
for j in a.iterkeys():
pya = a[j]
ma[<int> j] = pya.thisptr[0]
self.thisptr.process(ma)
finally:
del ma


Note that you must declare self PyB or self.thisptr would not be accessible.


Sturla





Robert Bradshaw

unread,
Dec 5, 2014, 11:47:07 AM12/5/14
to cython...@googlegroups.com
Currently, you must iterate over the dict inserting items manually
into the map.

- Robert
Reply all
Reply to author
Forward
0 new messages