【问题标题】:ctypes: construct pointer from arbitrary integerctypes:从任意整数构造指针
【发布时间】:2011-08-12 15:06:29
【问题描述】:

出于低级目的,我需要从任意地址构造一个 ctypes 指针,以整数形式给出。例如:

INTP = ctypes.POINTER(ctypes.c_int)
p = INTP(0x12345678) # i *know* this is the address

但所有这些尝试都会导致

TypeError: expected c_long instead of int

我能做些什么来克服这个问题吗?如果有人想知道我为什么需要这个,这样做是为了从 win32file.PyOVERLAPPED 中提取 OVERLAPPED 结构,用于将 ctypes 公开的函数与 win32file 包装的 API 集成。

谢谢,
-托默

【问题讨论】:

    标签: python ctypes pywin32


    【解决方案1】:

    您可以使用ctypes.cast(addr, type)。我将扩展您的示例以通过已知对象获取地址,以演示:

    INTP = ctypes.POINTER(ctypes.c_int)
    num = ctypes.c_int(42)
    addr = ctypes.addressof(num)
    print 'address:', addr, type(addr)
    ptr = ctypes.cast(addr, INTP)
    print 'pointer:', ptr
    print 'value:', ptr[0]
    

    输出:

    address: 4301122528 <type 'int'>
    pointer: <__main__.LP_c_int object at 0x1005decb0>
    value: 42
    

    【讨论】:

    • @sebulba:如果是,请将答案标记为正确,请:)
    • 那print('value:', ptr.contents)
    猜你喜欢
    • 2014-01-23
    • 1970-01-01
    • 2014-08-02
    • 1970-01-01
    • 1970-01-01
    • 2021-08-11
    • 1970-01-01
    • 1970-01-01
    • 2018-04-16
    相关资源
    最近更新 更多