如何从python ctypes取消引用内存位置? [英] How to dereference a memory location from python ctypes?

查看:104
本文介绍了如何从python ctypes取消引用内存位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在python ctypes中复制以下c代码:

I want to replicate the following c code in python ctypes:

main() {
  long *ptr = (long *)0x7fff96000000;
  printf("%lx",*ptr);
}

我可以弄清楚如何将此函数作为函数指针来调用只需进行正常的取消引用即可:

I can figure out how to call this memory location as a function pointer but not just do a normal dereference:

from ctypes import *
"""
>>> fptr = CFUNCTYPE(None, None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.6/ctypes/__init__.py", line 104, in CFUNCTYPE
    class CFunctionType(_CFuncPtr):
TypeError: Error when calling the metaclass bases
    item 1 in _argtypes_ has no from_param method
"""
fptr = CFUNCTYPE(None, c_void_p) #add c_void_p since you have to have an arg
fptr2 = fptr(0x7fff96000000)
fptr2(c_void_p(0))
#python: segfault at 7fff96000000 ip 00007fff96000000

因为那里是段错误指向该内存位置的指令指针正在成功调用它。但是我不能只读取内存位置:

Since there it is a segfault with the instruction pointer pointing to this memory location it is successfully calling it. However I can't get it to just read the memory location:

ptr = POINTER(c_long)
ptr2 = ptr(c_long(0x7fff96000000))
#>>> ptr2[0]
#140735709970432
#>>> hex(ptr2[0])
#'0x7fff96000000'
#>>> ptr2.contents
#c_long(140735709970432)


推荐答案

ctypes.cast

>>> import ctypes
>>> c_long_p = ctypes.POINTER(ctypes.c_long)
>>> some_long = ctypes.c_long(42)
>>> ctypes.addressof(some_long)
4300833936
>>> ctypes.cast(4300833936, c_long_p)
<__main__.LP_c_long object at 0x1005983b0>
>>> ctypes.cast(4300833936, c_long_p).contents
c_long(42)

这篇关于如何从python ctypes取消引用内存位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆