gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:59:03 24 4
gpt4 key购买 nike

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

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

我可以弄清楚如何将此内存位置作为函数指针调用,而不仅仅是进行正常的解引用:

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

由于存在段错误,指令指针指向该内存位置,因此成功调用了它。但是我不能让它只读取内存位置:

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 - 如何从 python ctypes 中取消引用内存位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1555944/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com