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.