pythonc++integerctypesuint64

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.


Solution

  • 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.