Re: [cython-users] Cython and stl::tuple

719 views
Skip to first unread message

Robert Bradshaw

unread,
Nov 18, 2012, 12:04:55 AM11/18/12
to cython...@googlegroups.com
On Sat, Nov 17, 2012 at 11:35 AM, Milos Davidovic <mil...@gmail.com> wrote:
> Can anybody give some hints about using stl::tuple in cython? A bunch of
> other stl containers can be easily imported from libcpp (list, vector, map)
> but there is no tuple :( Is some workaround possible?

Cython doesn't (yet) support variadic template arguments, or non-type
template arguments, which make wrapping tuples a bit problematic. I
would write small helper functions to convert between whatever tuple
types you need and a struct (which is basically just as powerful) and
include them as a header file.

- Robert

Robert Bradshaw

unread,
Nov 19, 2012, 2:30:15 PM11/19/12
to cython...@googlegroups.com
On Sun, Nov 18, 2012 at 2:42 AM, Milos Davidovic <mil...@gmail.com> wrote:
> Thanks for quick reply.
>
> I am writing a wrapper around c++ function that returns stl::map which has
> stl::tuple for key and value. I tried to typedef MyMapType in c++ and
> ctypedef it in pyx file so that I can write signatures for c++ helper
> functions. Unfortunately this doesn't work because compilation phase fails
> (cython successfully generates c++ file) with following error:
>
> error: invalid cast from type ‘MyMapType {aka std::map<std::tuple<int, int,
> int, int>, std::list<std::tuple<int, double, double, double> > >}’ to type
> ‘PyObject* {aka _object*}’
>
> This error corresponds to following snippet in pyx file:
>
> cdef MyMapType aMap
>
> cdef double temp
>
> aMap = some_external_cpp_func_that_returns_map(...)
>
> temp = helper_func(aMap)
>
> print temp
>
>
> Can I do something in Cython or do I need to modify c++ source to have
> structs as key and value?

You can't do anything in Cython to turn an arbitrary std::tuple into a
Python object. One question to ask is whether you really need to
convert this map into a Python object in the first place.

> Although in my specific case I could get away with
> vector[int] as key and struct as value, thus avoiding writing non
> method-less C structs.

Who says structs can't have methods, this is C++, right :-P.
Reply all
Reply to author
Forward
0 new messages