1

Is it possible to perform a mmap.read() (or equivalent) in Python without advancing the pointer?

I need to read the same address in a volatile memory over and over, and to optimise performance I don't want to have to seek to the same address each time.

file   = os.open("/dev/mem", os.O_RDWR | os.O_SYNC)
memory = mmap.mmap(f, 0x50000000, mmap.MAP_SHARED)

for index in range(1000000):
    memory.seek(address)

    # Unpack the bytes little-endian (least significant byte in first byte address etc.)
    data = struct.unpack("<L", memory.read(4))[0]

I hope someone can help.

Optimist
  • 93
  • 1
  • 5
  • Does this answer your question? [How to read from pointer address in Python?](https://stackoverflow.com/questions/48808997/how-to-read-from-pointer-address-in-python) – tevemadar Dec 05 '20 at 17:35
  • Try `memory[address:address+size]` since you can index mmap like a `bytearray`. – YiFei Dec 05 '20 at 17:36
  • Also look at https://stackoverflow.com/questions/8250625/access-memory-address-in-python - the common point is `ctypes` in them. And the `[]` suggestion sounds plausible too. – tevemadar Dec 05 '20 at 17:36
  • @YiFei data = memory[address:address + 3] nearly works. I want to read 4 bytes, but it does not work as expected. If one sets size to 4, I think 5 bytes will be read which is not the intention. – Optimist Dec 05 '20 at 17:49
  • @YiFei Actuallydata = memory[address:address + 4] works! Thank you so much! – Optimist Dec 05 '20 at 18:06

1 Answers1

0

The solution is as follows:

file   = os.open("/dev/mem", os.O_RDWR | os.O_SYNC)
memory = mmap.mmap(f, 0x50000000, mmap.MAP_SHARED)

for index in range(1000000):
    # Unpack the bytes little-endian (least significant byte in first byte address etc.)
    data = struct.unpack("<L", memory[address:address + 4])[0]

Thanks to @YiFei for the pointer. It has improved the speed of my code by 25%.

Optimist
  • 93
  • 1
  • 5