在 python c_types 的结构中读取空指针

Read void pointer inside a struct in python c_types

我有一个带有 void 指针成员的结构并试图打印它的值。我得到的类型是 int。我如何检索它的值。

下面是我的 python 代码,我如何读取 p 值。

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()

输出:

<class 'int'>

出于某种原因,设计 ctypes 的人认为在检索结构成员或数组元素或接收 c_void_p 时将 c_void_p 值透明地转换为 Python 整数是个好主意] 来自外部函数调用的值。您可以通过再次构造一个 c_void_p 来反转转换:

pointer_as_c_void_p = c_void_p(t.p)

如果要转换为整型指针,请使用cast:

pointer_as_int_pointer = cast(t.p, POINTER(c_int))

然后您可以索引指针以检索值,或将其切片以获取列表:

print(pointer_as_int_pointer[1]) # prints 2
print(pointer_as_int_pointer[:3]) # prints [1, 2, 3]