pythoncshared-librariesctypesunsigned-long-long-int

unexpected integer returned from a C function by calling it using ctypes


I wrote following C function:

unsigned long long int myfunction(unsigned long long int number)
{
    return number;
}

and after making a shared library I want to calling it from python:

from pathlib import Path
from ctypes import CDLL, c_ulonglong

cwd = Path.cwd()
so_file = Path.joinpath(cwd, Path("mylib.so"))
c_lib = CDLL(so_file)
c_func = c_lib.myfunction

if __name__ == '__main__':
    my_number = 844952973115541
    my_c_number = c_ulonglong(my_number)
    ans = c_ulonglong(c_func(my_c_number))
    print(ans.value)

I expect to get back the number I gave, but the following number returns:

18446744073471557781

Solution

  • They python code assumes the c function returns an int. You can fix it by adding:

    c_func.restype = c_ulonglong