简体   繁体   中英

python ctypes module how to transfer uint64_t from c++func return to python int,not set restype=c_long_long

i use python ctypes module to cal crc from c++ function it return uint64_t type. In python, i do not set restype(c_long_long), i get a python int value -870013293, however set restype the value is 14705237936323208851. can you tell me the relation about int_val and long_val.

Here is what is written in the documentation: https://docs.python.org/3/library/ctypes.html#module-ctypes

Python integers are passed as the platforms default C int type, their value is masked to fit into the C type.

Therefore, default the value is treated as c_int, and:

Represents the C signed int datatype. The constructor accepts an optional integer initializer; no overflow checking is done. On platforms where sizeof(int) == sizeof(long) it is an alias to c_long.

Since there is no overflow and the number is signed, instead of a large number, it can output any number from -2,147,483,648 to 2,147,483,647.(32 bits)

If you know the return value will be unsigned and explicitly type c_uint64 ( usually an alias for c_ulonglong), then you'll get the value you want.(64 bits)

The default return type for ctypes is c_int which is a 32-bit signed value. If you don't set .restype = c_uint64 for a 64-bit value, the return value is converted incorrectly from C to Python. You can see that the value was truncated to 32 bits if you display it in hexadecimal:

>>> hex(-870013293 & 0xFFFFFFFF)  # twos complement representation of a 32-bit negative value
'0xcc24a693'
>>> hex(14705237936323208851)     # the actual return value
'0xcc137ffdcc24a693'

Note that the last 32 bits of the 64-bit value match the 32-bit signed value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM