rgov
rgov

Reputation: 4329

Comparing simple Python ctypes data types

>>> ctypes.c_ushort(37099) == ctypes.c_ushort(37099)
False

These do not seem to be equal because there are no comparison operators for PyCSimpleType objects.

Is there a reason why these are omitted? It seems that one must use:

>>> ctypes.c_ushort(37099).value == ctypes.c_ushort(37099).value
True

Upvotes: 4

Views: 1265

Answers (1)

FThompson
FThompson

Reputation: 28687

According to the documentation of ctypes._SimpleCData and its superclass ctypes._CData, "all ctypes type instances contain a memory block that hold C compatible data."

Presumably, each invocation of ctypes.c_ushort(37099) corresponds to a new memory block, thus making the equality comparison between them false. The documentation also notes that the value attribute contains the actual value of the object.

>>> import ctypes
>>> val1 = ctypes.c_ushort(37099)
>>> val2 = ctypes.c_ushort(37099)
>>> ctypes.addressof(val1)
2193186894992
>>> ctypes.addressof(val2)
2193186895376

Upvotes: 3

Related Questions