This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: ctypes: problem with large integers
Type: Stage:
Components: Extension Modules Versions: Python 2.5
process
Status: closed Resolution: wont fix
Dependencies: Superseder:
Assigned To: theller Nosy List: belopolsky, theller
Priority: normal Keywords:

Created on 2007-04-19 21:51 by belopolsky, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Messages (4)
msg31837 - (view) Author: Alexander Belopolsky (belopolsky) * (Python committer) Date: 2007-04-19 21:51
Python 2.5 (r25:51908, Nov 24 2006, 11:03:50)
[GCC 3.4.4 20050721 (Red Hat 3.4.4-2)] on linux2
>>> from ctypes import *
>>> c_int(2**31).value
-2147483648
>>> c_long(2**32-1).value
-1

In a 64-bit build, the situation is even worse:

>>> c_int(int(2**32)).value
0
>>> c_int(2**32).value
0

Another way to see the problem:
>>> c = CDLL(None)
>>> c.printf("%d\n", 2**32)
0
2
msg31838 - (view) Author: Thomas Heller (theller) * (Python committer) Date: 2007-04-20 18:55
This works as designed.  ctypes intentionally does no overflow checking when using the c_int, c_uint, and related integer types.  Instead, only the available bits are used - just as in C.

Closing as invalid (sorry).
msg31839 - (view) Author: Alexander Belopolsky (belopolsky) * (Python committer) Date: 2007-04-20 19:37
An issue remains with the implicit conversion:

On a 64-bit platform (sizeof(long)=64):

>>> c.printf("%d\n",1<<64)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ctypes.ArgumentError: argument 2: <type 'exceptions.OverflowError'>: long int too long to convert

so it does do overflow checking, but

>>> c.printf("%d\n",(1<<64)-1)
-1
3
>>> c.printf("%d\n",(1<<32))
0
2

msg31840 - (view) Author: Thomas Heller (theller) * (Python committer) Date: 2007-07-13 17:51
I must say I do not care too much about the remaining issue.  To be portable between 32-bit and 64-bit platforms you should define .argtypes anyway or explicitely wrap the arguments into ctypes instances, if setting .argtypes is not possible as for printf.
History
Date User Action Args
2022-04-11 14:56:23adminsetgithub: 44869
2007-04-19 21:51:13belopolskycreate