2

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'>

1 Answer 1

2

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]
Sign up to request clarification or add additional context in comments.

3 Comments

Once i convert it to void_p, how do i convert it to integer pointer and read values?
@harry: Answer expanded.
got it, Thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.