[Cython] Automatic C++ conversions

Robert Bradshaw robertwb at gmail.com
Thu Jun 28 12:07:13 CEST 2012


On Thu, Jun 28, 2012 at 2:54 AM, Stefan Behnel <stefan_ml at behnel.de> wrote:
> 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?

Yes, we could. If we do that it'd make sense to special case list and
vector and pair and and map and set as well, though perhaps those are
special enough to hard code them, and it makes the language simpler to
not have more special methods.

> 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 ...

I don't think it'd be backwards compatible, currently it's just an error.

>> 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
> _______________________________________________
> cython-devel mailing list
> cython-devel at python.org
> http://mail.python.org/mailman/listinfo/cython-devel


More information about the cython-devel mailing list