如何在Python中获取mmap-ed内存的地址? [英] How to get the address of mmap-ed memory in Python?

查看:249
本文介绍了如何在Python中获取mmap-ed内存的地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法弄清楚如何在Python中(从mmap模块中)获取标准 mmap 对象的虚拟地址. 记录的方法似乎只能以字节数组或字符串的形式访问内存.

I cannot figure how to get the virtual address of the standard mmap objects in Python (from the mmap module). The documented methods only seem to access the memory as array of bytes or as character strings.

但是我需要一次精确地访问2个或4个字节的mmap'ped内存-因为在我的应用程序中此内存已映射到硬件寄存器(请考虑/dev/mem或GPIO等).可以通过 ctypes 模块以这种方式访问​​内存-但为此,我需要映射的 pointer (指针)或虚拟地址.

But I need to access the mmap'ped memory by precisely 2 or 4 bytes at once - because this memory in my application is mapped to hardware registers (think /dev/mem or GPIO or such). Accessing memory in this way is possible with ctypes module - but for this I need the pointer - or virtual address - of the mapping.

目前,我通过使用libc中的本机open()和mmap()函数(由于使用了相同的ctypes)克服了这一问题,但宁愿不这样做.

Currently I overcome this by using the native open() and mmap() functions from libc (thanks to the same ctypes) but would rather not.

为什么mmap模块无法提供获取内存地址的简便方法?希望我缺少明显的东西...

Why the mmap module won't provide easy way to get the memory address? Hope I'm missing something obvious...

-dd

推荐答案

mmap对象支持可写缓冲区接口,因此可以将ctypes类具有的from_buffer类方法与mmap对象一起使用用于获取共享mmap文件内存的ctypes对象的参数.

mmap objects support the writable buffer interface, so you can use the from_buffer class method that ctypes classes have with the mmap object as an argument to get a ctypes object that shares the memory of the mmap file.

buf = mmap.mmap(fd, mmap.PAGESIZE, mmap.MAP_SHARED, mmap.PROT_WRITE)
int_pointer = ctypes.c_int.from_buffer(buf)

这篇关于如何在Python中获取mmap-ed内存的地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆