我想在python ctypes中复制以下c代码:main() {long *ptr = (long *)0x7fff96000000;printf(%lx,*ptr);}我可以弄清楚如何将此内存位置称为函数指针,但不仅仅是执行正常的取消引用:from ctypes import * ...

我想在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 ctypes中取消引用内存位置?


基础教程推荐
猜你喜欢
- 一台使用python的计算机(Windows Server 2008)上允许的最大同时HTTP连接数是多少 2023-11-13
- Python 中 Elias Delta 编码详情 2023-08-08
- python中列表添加元素的几种方式(+、append()、ext 2022-09-02
- windows 安装python 2023-09-04
- Python-Anaconda 3 Spyder似乎导致Windows 10上的互联网中断 2023-11-13
- Python入门之字典的使用教程 2022-10-20
- 【python测试开发栈】python内存管理机制(一)—引用计数 2023-11-12
- Python列表内存重新分配问题 2023-11-11
- python-Linux:os.pipe()中的文件描述符未出现在/ dev / fd中 2023-11-11
- 重新启动后,Python进程停止响应SIGTERM / SIGINT 2023-11-13