2011-11-18 20 views
2

我想获得一个文件对象的内存在Python 2.5 Windows下的一个区块。(因为某些原因我不能使用新版本的这个任务。)如何在Python 2.5中作为文件对象访问一块内存?

所以作为输入我有一个pointersize让我们假设我只需要只读访问权限。

如果你想知道,我通过使用ctypes得到了这些,我需要使它们可用于需要文件处理程序(只读)的函数。

我考虑使用cStringIO但为了创建这样的对象我需要一个string对象。

+0

你有一个指针? Python中的指针是什么意思? –

+1

的含义与C中的相同 - 在数据所在的进程内存地址中。如何获得上述数据是一个完全不同的问题。 – jsbueno

+0

根据要求添加了详细信息:) – sorin

回答

6

你应该在那里使用ctypes。从Python 2.5 ctypes开始,已经在标准库上,所以对你来说是一个“胜利”的情况。

随着ctypes的,你可以构造一个代表更高层次的足尖这样一个Python对象:

import ctypes 
integer_pointer_type = ctypes.POINTER(ctypes.c_int) 
my_pointer = integer_pointer_type.from_address(your_address) 

然后,您可以寻址存储器内容作为一个Python索引对象,像 打印my_pointer [0]

这不会给你一个“文件一样的界面” - 尽管这将是微不足道的包裹一类具有“读取”和“寻找”身边有这样一个对象的方法:

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 

(未经测试 - 如果它不起作用,请写信给我 - 可以修复)

请注意,尝试在分配给您的数据结构的空间之外读取内存的操作与在C:在大多数情况下,是一个分段故障。

+0

我没有对它进行测试,但我认为给读取大小大于'self.size'是不好的。更好地检查它。也许可以在self.cursor + = len(res)的形式下将'self.cursor'的东西毫不夸张地放在'return res'之前,它涵盖了所有的情况。 – glglgl

相关问题