How to get the address of mmap-ed memory in Python?

一曲冷凌霜 提交于 2019-12-05 17:48:31

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)

Here is a more complete code that I need get working, with Python 2.7, on Linux:

import os, io
from mmap import *
from ctypes import *

winsize= 0
devmemfd= -1
curr_va=0
curr_base=0
devf = None
mm = None
ptr4 = None

def mm_init( path = 'test.dat' ) :
  global curr_va,winsize,devmemfd,mm,devf,ptr4
  devf = open( path, "rwb")
  devmemfd = devf.fileno()
  mm = mmap(devmemfd, PAGESIZE, MAP_SHARED, PROT_WRITE) # this FAILS if MAP_SHARED
  ptr4 = POINTER(c_uint32)( c_uint32.from_buffer(mm) ) # this FAILS is I make mapping readonly
  curr_va = cast(ptr4, c_void_p).value 
  winsize=PAGESIZE
  print("OK")

Again, I should be missing something obvious as I'm new to Python

-- dd

Traceback:

>>> mm_init()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "mm-test.py", line 17, in mm_init
    mm = mmap(devmemfd, PAGESIZE, MAP_SHARED, PROT_WRITE) 
mmap.error: [Errno 13] Permission denied
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!