如何在Python ctypes中读取结构体的void指针成员指向的值
获取void指针指向的实际值
Ah, I get it, let's break this down for you. The reason type(t.p) shows <class 'int'> is totally normal in ctypes—c_void_p gets converted to an integer representing the memory address when you access it in Python, not a pointer object you can directly dereference.
To get the actual values that pointer points to, you need to cast that integer address back to the correct pointer type matching the original data (which is a c_int array in your case). Here's how to modify your code to access the values:
from ctypes import Structure, c_void_p, c_int, cast, POINTER class MyStruct(Structure): _fields_ = [ ("p", c_void_p) ] def test(): t = MyStruct() val = [1, 2, 3] arr_type = c_int * len(val) v = arr_type(*val) t.p = cast(v, c_void_p) # Method 1: Cast back to a pointer to c_int, access via index int_pointer = cast(t.p, POINTER(c_int)) print(int_pointer[0], int_pointer[1], int_pointer[2]) # Output: 1 2 3 # Method 2: Cast back to the exact array type, use as an array array_pointer = cast(t.p, POINTER(arr_type)) # Use [0] to get the actual array object from the pointer print(array_pointer[0][0], array_pointer[0][1], array_pointer[0][2]) # Output: 1 2 3 if __name__ == '__main__': test()
A couple of key notes to keep in mind:
- If you don't know the length of the array upfront, you'll want to add an extra field to your
MyStructto store the length—otherwise you won't be able to safely iterate over all elements. - Make sure the memory the pointer points to is still valid. In your example,
vis a local variable insidetest(), so as long as you accesst.pwhilevis still in scope, you're fine. Ifvgets garbage collected,t.pbecomes a dangling pointer and accessing it will cause errors.
内容的提问来源于stack exchange,提问作者harry
相关产品推荐
相关产品推荐

