[Cython] Automatic C++ conversions

Stefan Behnel stefan_ml at behnel.de
Thu Jun 28 11:54:49 CEST 2012


Robert Bradshaw, 28.06.2012 10:59:
> I've been looking how painful it is to constantly convert between
> Python objects and string in C++.

You mean std::string (as I think it's called)? Can't we just special case
that in the same way that we special case char* and friends? Basically just
one type more in that list. And it would give you efficient
encoding/decoding more or less for free.

I mean, well, it would likely break existing code to start doing that (in
the same way that we broke code by enabling type inference for convertible
pointers), but as long as it helps more than it breaks ...


> Yes, it's easy to write a utility,
> but this should be as natural (if not more so, as the length is
> explicit) than bytes <-> char*. Several other of the libcpp classes
> (vector, map) have natural Python analogues too.

And you would want to enable coercion to those, too? Have a vector copy
into a Python list automatically? (Although that's trivially done with a
list comprehension, maybe the other way is more interesting...)

I think, as long as there is one obvious mapping for a given type, I
wouldn't mind letting Cython apply it automatically.


> What would people think about making it possible to declare these in a
> C++ file? Being able to make arbitrary mappings anywhere between types
> is contextless global state that I'd rather avoid, but perhaps special
> methods defined on the class such as
> 
> cdef extern from "<string>" namespace "std":
>     cdef cppclass string:
>         def __object__(sting s):
>             return s.c_str()[s.size()]
>         def __create__(object o):
>             return string(<char*>o, len(o))
>         ...
> 
> (names open to suggestions) Then one could write
> 
> cdef extern from *:
>     string c_func(string)
> 
> def f(x):
>     return c_func(x)

Admittedly, it fits somewhat more naturally into C++ classes than generally
into C, although we could allow the same thing in ctypedefs.

However, I'm reluctant to introduce something like this as long as we can
get away with built-in auto-coercion.

Stefan


More information about the cython-devel mailing list