sor*_*rin 2 python ctypes python-2.5
我想获得一个文件对象的内存在Python 2.5 Windows下的一个区块.(因为某些原因我不能使用此任务更新的版本.)
所以作为输入我有一个pointer和一个size,让我们假设我只需要只读访问.
如果你想知道,我通过使用ctypes得到了这些,我需要让它们可用于需要文件处理程序的函数(只读).
我考虑过使用cStringIO但是为了创建这样的对象,我需要一个string对象.
你应该在那里使用ctypes.截至Python 2.5 ctypes已经在标准库上,所以对你来说是"胜利"的情况.
使用ctypes,你可以构造一个代表更高级别的pointe的python对象:
import ctypes
integer_pointer_type = ctypes.POINTER(ctypes.c_int)
my_pointer = integer_pointer_type.from_address(your_address)
Run Code Online (Sandbox Code Playgroud)
然后,您可以将内存内容作为Python索引对象来处理,例如print my_pointer [0]
这不会给你一个"类似接口的文件" - 虽然用这样一个对象包装一个带有"read"和"seek"方法的类是微不足道的:
class MyMemoryFile(object):
def __init__(self, pointer, size=None):
integer_pointer_type = ctypes.POINTER(ctypes.c_uchar)
self.pointer = integer_pointer_type.from_address(your_address)
self.cursor = 0
self.size = size
def seek(self, position, whence=0):
if whence == 0:
self.cursor = position
raise NotImplementedError
def read(size=None):
if size is None:
res = str(self.pointer[cursor:self.size])
self.cursor = self.size
else:
res = str(self.pointer[self.cursor:self.cursor + size]
self.cursor += size
return res
Run Code Online (Sandbox Code Playgroud)
(未经测试 - 如果不起作用,请写信给我 - 可以修复)
请注意,尝试读取超出为数据结构分配的空间的内存将与在C中执行此操作具有完全相同的效果:在大多数情况下,分段错误.
| 归档时间: |
|
| 查看次数: |
464 次 |
| 最近记录: |