这是不一致的:
from ctypes import *
class S(Structure):
_fields_ = [("x", POINTER(c_int)), ("y", c_int)]
o = S()
print o.x
print o.y
返回
<__main__.LP_c_int object at 0x10d3d08c0>
0
因此,在一种情况下,它返回ctypes
类型,在另一种情况下,它直接返回值。
我有一些更通用的代码,我总是需要传递一个ctypes
类型的实例(也是可写的,即写入它意味着在上面的例子中修改o
)。对于o.x
,这没关系。但不适用于o.y
。
如何获取c_int
的{{1}}个实例?
答案 0 :(得分:1)
从_ctypes
来源看,它们在包装时不会对简单的ctypes实例进行这种聪明的自动转换。
所以一个(丑陋的)解决方案是:
from ctypes import *
def WrapClass(c):
class C(c): pass
C.__name__ = "wrapped_" + c.__name__
return C
class S(Structure):
_fields_ = [("x", POINTER(c_int)), ("y", WrapClass(c_int))]
o = S()
print o.x
print o.y
print o.y.value
答案 1 :(得分:0)
起初我虽然对于'普通'类型只是一个不同的 repr 方法,但经过一些测试后我认为肯定会有一些时髦的东西。如果某种东西存在于结构中,那确实会产生影响。
from ctypes import *
class S(Structure):
_fields_ = [("x", POINTER(c_int)), ("y", c_int), ("z", c_float)]
o = S()
x = POINTER(c_int)
y = c_int(1)
z = c_float(2.2)
print("In structure: x:{}, y:{}, z:{}".format(o.x, o.y, o.z))
print("Out of structure: x:{}, y:{}, z:{}".format(x, y, z))
在结构中:x:&lt; main .LP_c_long对象位于0x000000000A090EC8&gt;,y:0,z:0.0
超出结构:x:,y:c_long(1),z:c_float(2.200000047683716)
特别是,我认为这应该被认为是错误行为:
o.x.contents = y #OK
o.x.contents = o.y #not OK!!
追踪(最近一次通话): 文件“”,第1行,in TypeError:期望c_long而不是int