【发布时间】:2020-08-18 18:27:39
【问题描述】:
我需要在内存中分配一定的空间,为此我一直使用VirtualAlloc。
然而,我越来越注意到VirtualAlloc 返回一个超过 32 位的地址,尽管总是小于 33 位。
结果就是当我把数据复制到这个内存地址的时候,电脑就死机了。
我正在使用 64 位 Windows 和 64 位 Python。我怀疑将数据复制到内存的程序只能处理 32 位。有没有办法强制VirtualAlloc 提供 32 位内的地址?
我正在使用Python,特别是ctypes 包来调用VirtualAlloc,请参见下面的代码。
多次执行此代码会更改地址,因此重复调用下面的函数最终会导致地址低于 32 位。但是,我正在寻找问题的原因和故障安全解决方案。任何帮助将不胜感激。
import ctypes
mem_commit = 0x1000
page_readwrite = 0x4
size_bytes = 200000 # Allocation sizes are usually around this value
ctypes.windll.kernel32.VirtualAlloc.argtypes = [
ctypes.c_void_p, ctypes.c_long, ctypes.c_long, ctypes.c_long]
ctypes.windll.kernel32.VirtualAlloc.restype = ctypes.c_int
addr = ctypes.windll.kernel32.VirtualAlloc(
0, ctypes.c_long(size_bytes), mem_commit, page_readwrite)
请注意,我之后使用 VirtualFree 释放了内存。
【问题讨论】:
-
我认为崩溃是由于您传递给“内存复制功能”的
addr中包含的截断值。见this answer。
标签: python memory ctypes kernel32 virtualalloc