这是我尝试做的一个例子:
import ctypes
MEM_SIZE = 1024*1024*128
# allocate memory (this is Windows specific)
ptr = ctypes.cdll.msvcrt.malloc(MEM_SIZE)
# make memory accessible to Python calls
mem = ctypes.string_at(ptr, MEM_SIZE)
# BAD: string_at duplicates memory
# store it to disk
open(r'test.raw', 'wb').write(mem)
简而言之:我有一个普通的内存指针,我知道块的大小,并希望将其存储在磁盘上或将其重新用作numpy数组。
如何在不生成内存块副本的情况下执行此操作?
相关问题:stackoverflow: Fill python ctypes pointer(感谢Brian Larsen提示)
答案 0 :(得分:2)
ctypes_array = (ctypes.c_char * MEM_SIZE).from_address(ptr)
with open('test.raw', 'wb') as f:
f.write(ctypes_array)
numpy_array = numpy.frombuffer(ctypes_array, dtype=numpy.byte)
numpy_array.tofile('test.raw')