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.

Title: ctypes incorrect handling of long int on 64bits Linux
Type: behavior Stage: resolved
Components: ctypes Versions: Python 2.7
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: Marco Clemencic, eryksun, terry.reedy
Priority: normal Keywords:

Created on 2015-06-19 08:35 by Marco Clemencic, last changed 2022-04-11 14:58 by admin. This issue is now closed.

File name Uploaded Description Edit
test_py.tar.bz2 Marco Clemencic, 2015-06-19 08:35 minimal test case exposing the problem
Messages (5)
msg245494 - (view) Author: Marco Clemencic (Marco Clemencic) Date: 2015-06-19 08:35
When passing a Python int to a C function expecting long int (or void*) via ctypes, the number gets truncated to 32 bits, even if the args types are correctly declared.
The workaround is to wrap the argument in c_long (or c_void_p), but the automatic unwrapping of c_long (or c_void_p) in the return type lead to undefined behaviour in code like:

myClib.getNumber.restype = c_long
myClib.doSomething.args = [c_long]
l = myClib.getnumber()
msg245495 - (view) Author: Eryk Sun (eryksun) * (Python triager) Date: 2015-06-19 09:15
It works for me:

    >>> open('test.c', 'w').write('long test(long x) {return x;}')
    >>> os.system('gcc -shared -fPIC -o test.c')
    >>> test = CDLL('./').test
    >>> test.restype = c_long
    >>> test.argtypes = (c_long,)
    >>> test(2**63-1) == 2**63-1

However, I used the correct attribute name, "argtypes". ctypes objects have dicts to allow setting arbitrary attribute names, so you won't get an AttributeError when setting "args" on a function pointer.
msg245525 - (view) Author: Terry J. Reedy (terry.reedy) * (Python committer) Date: 2015-06-19 20:01
Should this then be closed as not a bug?
msg246933 - (view) Author: Marco Clemencic (Marco Clemencic) Date: 2015-07-19 07:54

apologies for the very late answer, but I just discovered that the mails got flagged as spam :(

In any case, I do not know where I got this "args" from, but I can confirm that the problem is just a bug on my side.

msg246934 - (view) Author: Terry J. Reedy (terry.reedy) * (Python committer) Date: 2015-07-19 08:44
Thank you for following up on this.
Date User Action Args
2022-04-11 14:58:18adminsetgithub: 68658
2015-07-19 08:44:58terry.reedysetmessages: + msg246934
stage: resolved
2015-07-19 07:54:25Marco Clemencicsetstatus: open -> closed
resolution: not a bug
messages: + msg246933
2015-06-19 20:01:12terry.reedysetnosy: + terry.reedy
messages: + msg245525
2015-06-19 09:15:52eryksunsetnosy: + eryksun
messages: + msg245495
2015-06-19 08:35:40Marco Clemenciccreate