python 如何从python ctypes取消引用内存位置?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1555944/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 22:34:14  来源:igfitidea点击:

How to dereference a memory location from python ctypes?

pythonctypesffi

提问by habnabit

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

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

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)

回答by habnabit

ctypes.cast.

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)