ctypes:从任意整数构造指针

发布于 2024-11-03 07:30:19 字数 424 浏览 3 评论 0原文

出于低级目的,我需要从任意地址(以整数给出)构造一个 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 集成。

谢谢,
-托默

For low-level purposes, I need to construct a ctypes pointer from an arbitrary address, given as an integer. For instance:

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

But all such attempts result in

TypeError: expected c_long instead of int

Is there anything I can do to overcome this? In case someone wonders why I need this, it's done so as to extract the OVERLAPPED struct from a win32file.PyOVERLAPPED, for integrating ctypes-exposed functions with win32file wrapped APIs.

Thanks,
-Tomer

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

嘿咻 2024-11-10 07:30:19

您可以使用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

You can use ctypes.cast(addr, type). I'll extend your example to acquire an address via a known object, to demonstrate:

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]

Output:

address: 4301122528 <type 'int'>
pointer: <__main__.LP_c_int object at 0x1005decb0>
value: 42
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文