You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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 MyStruct to 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, v is a local variable inside test(), so as long as you access t.p while v is still in scope, you're fine. If v gets garbage collected, t.p becomes a dangling pointer and accessing it will cause errors.

内容的提问来源于stack exchange,提问作者harry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 23:42:45