ctype.c_long.from_address returns random value for some inputs

514 Views Asked by At

See this code:

>>> import ctypes
>>> x=12345
>>> y=x
>>> ctypes.c_long.from_address(id(x)).value
2
>>> a=2
>>> b=a
>>> ctypes.c_long.from_address(id(a)).value
116
>>>

for object x it returned expected output but for "a" it's returning an unexpected result

2

There are 2 best solutions below

0
On

I think this happens because you are reading a Python int object using the C long format. You are asking Python to read starting from id(a) which is an address holding an object of int in Python. Starting from this address you are asking Python to read data as C long which is binary bits in two's complement.

2
On

The "expected value" is refcount of an allocated object.

When you assigned x, you allocated a new int object. You took another reference, and were unsurprised to see the refcount increment by 1.

When you assigned a, you took a reference on an existing object. The cPython interpreter pre-created a cache of more than two hundred small integers, and then modules you imported took references to some of them. Your example output is just saying there are more than a hundred references extant, cf What's with the integer cache maintained by the interpreter?.