Reputation: 1095
I've a struct with void pointer member and trying to print it's value. I'm getting the type as int. How do i retrieve it values.
Below is my python code, How do i read p values.
class MyStruct(Structure):
_fields_ = [
("p", c_void_p)
]
def test():
t = MyStruct()
val = [1, 2, 3]
v = (c_int * len(val) )(*val)
t.p = cast(v, c_void_p)
print(type(t.p))
if __name__ == '__main__':
test()
Output:
<class 'int'>
Upvotes: 2
Views: 519
Reputation: 281262
For some reason, whoever designed ctypes decided it would be a good idea to transparently convert c_void_p
values to Python ints when you retrieve struct members or array elements, or receive c_void_p
values from foreign function calls. You can reverse the transformation by constructing a c_void_p
again:
pointer_as_c_void_p = c_void_p(t.p)
If you want to convert to pointer-to-int, use cast
:
pointer_as_int_pointer = cast(t.p, POINTER(c_int))
You can then index the pointer to retrieve values, or slice it to get a list:
print(pointer_as_int_pointer[1]) # prints 2
print(pointer_as_int_pointer[:3]) # prints [1, 2, 3]
Upvotes: 2