Python int overflows when calling ctypes functions

I play with ctypes ... I have the following C code

Change The reason I'm trying to figure this out is to make this blog post more correct.

sumrange.c

#include <stdio.h> long sumrange(long); long sumrange(long arg) { long i, x; x = 0L; for (i = 0L; i < arg; i++) { x = x + i; } return x; } 

which I compile with the following command (on OSX)

 $ gcc -shared -Wl,-install_name,sumrange.so -o ./sumrange.so -fPIC ./sumrange.c 

I implemented the same function in python:

 pysumrange = lambda arg: sum(xrange(arg)) 

Then I run both in an interactive shell:

 >>> import ctypes >>> sumrange = ctypes.CDLL('./sumrange.so') >>> pysumrange = lambda arg: sum(xrange(arg)) >>> print sumrange.sumrange(10**8), pysumrange(10**8) ... 887459712 4999999950000000 

... and the numbers do not match. Why should it be?

I tried using unsigned long long for all variables in C code with no effect (same output).

+4
source share
1 answer

long is a 32-bit type, so C code just overflows.

Python doesnt; pysumrange gives the correct answer.

ctypes does not know that the return type of functions is unsigned long long unless you report it. See the return data types in the Python Standard Library documentation. It says:

By default, functions are assumed to return a C type int . Other types of returned data can be specified by setting the restype attribute of the restype object.

Therefore, perhaps by doing this, before calling the function, you will work for you:

 sumrange.sumrange.restype = ctypes.c_ulonglong 
+4
source

Source: https://habr.com/ru/post/1433875/


All Articles