[Cython] calling gmp automatically
Dag Sverre Seljebotn
dagss at student.matnat.uio.no
Tue Dec 23 15:06:00 CET 2008
Ondrej Certik wrote:
> On Tue, Dec 23, 2008 at 2:46 PM, Dag Sverre Seljebotn
> <dagss at student.matnat.uio.no> wrote:
>> Ondrej Certik wrote:
>>> Preferably one could use it like this:
>>>
>>> cdef mpz tmp
>>> tmp = den/f.v[i]
>>> vec[0][i] = f.v[i]*tmp
>>>
>>> or something like that and leave it to Cython to call the correct
>>> methods. I don't like the fact that Cython would have to be gmp aware
>>> --- maybe there is some way to just implement a cdef class mpz that
>>> would support __add__, __mull__ and things like that, so as to behave
>>> just like python integer, but still be as fast as the explicit code
>>> above.
>>
>> Yep. Operator overloading using inline cdef functions should be a very
>> non-controversial feature to add to Cython, and not very difficult to
>> add
>> either (transform from eg. BinopNode to SimpleCallNode in the right
>> circumstances), and that would solve this problem in a much more generic
>> way. At first that would require one to create a "cdef class" wrapper
>> class containing the struct as a member and the overloaded operators,
>> but
>> when that is all working one could discuss allowing such overloads in
>> structs as well?
>
> Yes, I was thinking of something like this. How would this work
> technically?
>
> cdef class mpz:
> cdef __cinit__(...)
> pass
> cdef inline __add__(a, b):
> cdef mpz tmp
> mpz_add(a.thisptr, b.thisptr, tmp)
> return tmp
>
> So Cython would inline this.
Well, it's not supported now, so right now Cython wouldn't do anything.
But if supported then the add function would be emitted to C with the
INLINE modifier, and gcc can then inline it.
That does give the overhead of creating and refcounting a Python object,
but it is a good first goal at least. To get around that one could discuss
allowing something like this:
cdef extern from ...:
cdef struct mpz_t:
cdef inline mpz_t __add__(mpz_t a, mpz_t b):
mpz_t result
...
return result
or perhaps
cdef extern from ...:
cdef struct mpz_t:
cdef inline int __add__(mpz_t* a, mpz_t* b, mpz_t* result) except -1:
...
However it's a question of just how much of C++ we want to reimplement :-)
Dag Sverre
More information about the Cython-dev
mailing list