当我创建类型为ctype.c_int
的变量时,它会报告该类型,并且不允许任何数学运算:
In [107]: x = c_int(1)
In [108]: x
Out[108]: c_int(1)
In [109]: x+=1
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
----> 1 x+=1
TypeError: unsupported operand type(s) for +=: 'c_int' and 'int'
In [110]: x+=x
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
----> 1 x+=x
TypeError: unsupported operand type(s) for +=: 'c_int' and 'c_int'
In [111]: type(x)
Out[111]: ctypes.c_int
另一方面:当我制作一个内部有c_int
的 struct 时,它被报告为int
,允许数学运算,但似乎仍然被存储为32位c整数,因为它正确地包装在32位上,并且在位置31处尊重符号位.
In [112]: class REC(ctypes.Structure): _fields_=[('x',ctypes.c_int),('y',ctypes.c_int)]
In [113]: rec = REC()
In [114]: rec.x
Out[114]: 0
In [114]: type(rec.x)
Out[114]: int # why not ctypes.c_int ???
In [116]: rec.x+=0x7FFFFFFF # += works, so it is regular python int ?
In [117]: rec.x
Out[117]: 2147483647
In [118]: rec.x+=1
In [119]: rec.x
Out[119]: -2147483648 # but it honors sign bit at position 31...
In [122]: rec.x=0xFFFFFFFF
In [123]: rec.x
Out[123]: -1
In [124]: rec.x+=1
In [125]: rec.x
Out[125]: 0 # ...and it wraps on 32 bits, so it is NOT python int!
有人能解释这种行为吗?这背后有什么逻辑吗?