On 2015-05-03 22:47, Vincent Delecroix wrote:
Hello,

How do we convert Python object to a C long in Cython? The following
does not work properly as rationals or float gets converted (to their floor)

def f(u):
     cdef long u_long = u

Well, Cython gave you what you asked for :-)

Cython considers C long (or other C integral types I guess) to correspond to Python "int" or "long". So your code is really the Cython version of

u_long = int(u)

which does indeed return the floor (analogous to floats, so this is not a bug in itself).

What you want here is __index__:

sage: (2/3).__index__()
TypeError: rational is not an integer

In Cython, you call PyNumber_Index():

from cpython.number cimport PyNumber_Index
def f(u):
    cdef long u_long = PyNumber_Index(u)


Jeroen.

--
You received this message because you are subscribed to the Google Groups 
"sage-support" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/sage-support.
For more options, visit https://groups.google.com/d/optout.

Reply via email to