2

我想在 Windows 下的 Python 2.5 中获取一个内存块的文件对象。(由于某些原因,我不能为这个任务使用较新的版本。)

因此,作为输入,我确实有 apointer和 a size,假设我只需要只读访问权限。

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

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

4

2 回答 2

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 索引对象来寻址,例如 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

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

请注意,尝试读取超出为数据结构分配的空间的内存将产生与在 C 中完全相同的效果:在大多数情况下,会出现分段错误。

于 2011-11-18T11:12:58.120 回答
1

ctypes文档中,您似乎可以使用函数从内存中ctypes.string_at()地址获取字符串。

问题是字符串不是可变的,这意味着您将无法从 python 修改生成的字符串。要在 python 中有一个可变缓冲区,您需要从 python 调用该ctypes.create_string_buffer()函数

于 2011-11-18T11:11:01.737 回答